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

import android.app.Activity;
import android.app.Application;
import android.widget.TextView;

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.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.core.table.TableBean;
import com.gingersoft.gsa.cloud.common.core.user.UserContext;
import com.gingersoft.gsa.cloud.common.logan.LoganManager;
import com.gingersoft.gsa.cloud.common.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.common.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.database.bean.Discount;
import com.gingersoft.gsa.cloud.order.bean.discount.CouponDiscountBean;
import com.gingersoft.gsa.cloud.order.bean.request.OrderDiscountRequest;
import com.gingersoft.gsa.cloud.order.bean.response.OrderDiscountResponse;
import com.gingersoft.gsa.cloud.order.bean.response.OrderResponse;
import com.gingersoft.gsa.cloud.order.billItem.BillItem;
import com.gingersoft.gsa.cloud.order.billItem.DiscountItem;
import com.gingersoft.gsa.cloud.order.billItem.RoundingItem;
import com.gingersoft.gsa.cloud.order.billItem.ServiceChargeItem;
import com.gingersoft.gsa.cloud.order.cart.ShoppingCart;
import com.gingersoft.gsa.cloud.order.cart.ShoppingCartNumberChange;
import com.gingersoft.gsa.cloud.order.commodity.OrderDetail;
import com.gingersoft.gsa.cloud.order.discount.MemberCouponDiscount;
import com.gingersoft.gsa.cloud.order.discount.NomalDiscount;
import com.gingersoft.gsa.cloud.order.order.BaseOrder;
import com.gingersoft.gsa.cloud.order.order.DoshokuOrder;
import com.gingersoft.gsa.cloud.order.order.OrderFactory;
import com.gingersoft.gsa.cloud.order.order.TakeawayOrder;
import com.gingersoft.gsa.cloud.table.mvp.contract.BaseOrderContract;
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.presenter.mealstand.MealStandPresenter2;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.MealStandActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.MealStandActivity2;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.OrderContentActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.BillItemAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.SelectMealAdapter2;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.mealstand.SetMealFragment;
import com.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.DeviceUtils;
import com.jess.arms.utils.PermissionUtil;
import com.jess.arms.utils.RxLifecycleUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;

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

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import okhttp3.FormBody;
import okhttp3.RequestBody;

import static com.gingersoft.gsa.cloud.order.commodity.OrderDetail.DISCOUNT_TYPE;


/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2020-01-11
 * 修订历史：2020-01-11
 * 描述：
 */
@ActivityScope
public abstract class BaseOrderPresenter2<M extends BaseOrderContract.Model, V extends BaseOrderContract.View> extends BasePresenter<BaseOrderContract.Model, BaseOrderContract.View> {

    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    AppManager mAppManager;

    protected M mModel;
    protected V mRootView;

    protected BaseOrderPresenter2 mBaseOrderPresenter;

    private Activity IActivity;
    private MealStandActivity2 mMealStandActivity;
    private OrderContentActivity mOrderContentActivity;
    private MealStandPresenter2 mMealStandPresenter;

    /**
     * 訂單美食適配器
     */
    protected SelectMealAdapter2 mSelectMealAdapter;
    /**
     * 賬單項適配器
     */
    protected BillItemAdapter mBillItemAdapter;
    /**
     * 美食列表
     */
    protected List<OrderDetail> mOrderMealList;
    /**
     * 賬單項列表
     */
    protected List<BillItem> mBillItemList;
    /**
     * 餐檯信息
     */
    public TableBean.DataBean mTableInfo;
    /**
     * 訂單信息
     */
//    protected BaseOrder mOrder;
    /**
     * 堂食訂單信息
     */
    protected DoshokuOrder mDoshokuOrder;
    /**
     * 外賣訂單信息
     */
    protected TakeawayOrder mTakeawayOrder;
    /**
     * 美食購物車
     */
    protected ShoppingCart mShoppingCart;
    /**
     * 已下單信息
     */
    private OrderResponse orderPlaced;

    protected String cashStr = "$";
    protected String serviceChargeStr = "服務費";
    protected String roundingStr = "賬單小數";
    private final String noFoodDeliveryTip = "賬單沒有食品，是否開台?";


    public abstract void createOrder(boolean isPrint, Class<?> afterToActivity);

    public abstract void addOrderFood(boolean isPrint, Class<?> afterToActivity);

    public void saveCreateTime(long createTime) {
        if (mDoshokuOrder == null) {
            mDoshokuOrder.setOpenTableInfo(new TableBean.DataBean());
        }
        mDoshokuOrder.getOpenTableInfo().setCreateTime(TimeUtils.getTime(createTime, TimeUtils.DEFAULT_DATE_FORMAT));
    }

    public BaseOrderPresenter2(BaseOrderContract.Model model, BaseOrderContract.View rootView) {
        super(model, rootView);
        this.mModel = (M) model;
        this.mRootView = (V) rootView;
        this.mBaseOrderPresenter = this;

        if (mRootView instanceof SetMealFragment) {
            this.IActivity = (MealStandActivity2) ((SetMealFragment) mRootView).getActivity2();
        } else {
            if (IActivity instanceof MealStandActivity2) {
                mMealStandActivity = (MealStandActivity2) IActivity;
            } else if (IActivity instanceof OrderContentActivity) {
                mOrderContentActivity = (OrderContentActivity) IActivity;
            }
        }
        if (this instanceof MealStandPresenter2) {
            mMealStandPresenter = (MealStandPresenter2) this;
        }

        BaseOrder baseOrder = OrderFactory.createOrder(BaseOrder.orderType);
        if (BaseOrder.isTableToMeal()) {
            mDoshokuOrder = (DoshokuOrder) baseOrder;
            mTableInfo = mDoshokuOrder.getOpenTableInfo();
        } else {
            mTakeawayOrder = (TakeawayOrder) baseOrder;
        }
        mShoppingCart = baseOrder.getShoppingCart();
        mOrderMealList = mShoppingCart.getOrderCommodityList();
        mBillItemList = mShoppingCart.getBillItemList();

        if (mMealStandPresenter != null && mDoshokuOrder != null) {
            orderPlaced = mDoshokuOrder.getOrderPlaced();
        }

        resetSelected();
        initOrderAdapter();
        initItemClickListener();

        updateBillInfo();
    }

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

    private void initOrderAdapter() {
        if (mSelectMealAdapter == null) {
            mSelectMealAdapter = new SelectMealAdapter2(IActivity, mOrderMealList, this);
            //設置子父級下標
            mSelectMealAdapter.setIndex();
        }
        if (mBillItemAdapter == null) {
            mBillItemAdapter = new BillItemAdapter(IActivity, mBillItemList, cashStr);
        }
    }

    private void initItemClickListener() {
        mSelectMealAdapter.setOnItemClickListener(new SelectMealAdapter2.OnItemClickListener() {

            @Override
            public void onItemClick(OrderDetail datasBean, int position) {
                mRootView.recordOperat(true);
            }

            @Override
            public void onMealCountDelete(OrderDetail datasBean, int position) {
                mRootView.recordOperat(true);
                if (datasBean.getNumber() == 1) {
                    mSelectMealAdapter.removeFoodItem();
                    mSelectMealAdapter.notifyDataSetChanged();
                    updateBillInfo();
                } else {
                    changeNumber(datasBean.getNumber() - 1);
                }
            }

            @Override
            public void onMealCountAdd(OrderDetail datasBean, int position) {
                mRootView.recordOperat(true);
                changeNumber(datasBean.getNumber() + 1);
            }

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

    public void updateBillInfo() {
        updateBillInfo(null);
    }

    /**
     * 更新賬單信息
     * 1、更新食品折扣
     * 2、更新合計
     * 3、更新食品折扣
     * 4、更新服務費項{@link ServiceChargeItem}
     * 5、更新賬單折扣項{@link NomalDiscount}
     * 6、更新賬單小數項{@link RoundingItem}
     * 7、更新總金額
     */
    public void updateBillInfo(UpdateBillInfoEndListener updateBillInfoEndListener) {

        mShoppingCart.resetBeforeBillCalculation();
        //更新食品折扣
        updateFoodDiscount();
        //更新合計
        double wholeAmount = getFoodTotal();
        mShoppingCart.setWholeAmount(wholeAmount);

        LoganManager.w_tableMode(TAG, "合計金額=" + wholeAmount);

        Disposable disposable = Observable.just(wholeAmount)
                .subscribeOn(Schedulers.computation())
                /**
                 * 計算服務費(堂食)
                 */
                .map(new Function<Double, Double>() {
                    @Override
                    public Double apply(Double totalAmount) throws Exception {
                        if (mDoshokuOrder != null) {
                            int serviceCharge = mDoshokuOrder.getOpenTableInfo().getServiceCharge();
                            if (serviceCharge > 0) {
                                ServiceChargeItem item = new ServiceChargeItem(serviceChargeStr);
                                double serviceChargeMoney = getServiceableAmout();
                                totalAmount = item.updateBillItem(serviceChargeMoney, serviceCharge);
                                if (Double.doubleToLongBits(item.getMoney()) != 0.0) {
                                    mBillItemList.add(item);
                                    mShoppingCart.setServiceCharge(item.getMoney());
                                }
                                LoganManager.w_tableMode(TAG, "服務費=" + serviceChargeMoney);
                                LoganManager.w_tableMode(TAG, LoganManager.EVENT_CALCULATE, "服務費後總金額=" + totalAmount);
                            }
                        }
                        return totalAmount;
                    }
                })
                /**
                 * 計算折扣
                 */
                .map(new Function<Double, Double>() {
                    @Override
                    public Double apply(Double totalAmount) throws Exception {
                        if (mMealStandActivity != null && orderPlaced != null) {

                            //添加已送單折扣
                            List<OrderDiscountResponse> orderDiscounts = orderPlaced.getDiscountDetails();
                            if (orderDiscounts != null) {
                                for (OrderDiscountResponse orderDiscount : orderDiscounts) {
                                    if (orderDiscount.getType() == OrderDiscountRequest.ORDER_DISCOUNT) {
                                        LoganManager.w_tableMode(TAG, "已下單整單折扣金額=" + orderDiscount.getDiscountAmount());
                                        //整單折扣
                                        Discount discount = new Discount();
                                        discount.setId(orderDiscount.getDiscountId());
                                        discount.setDiscountRecordId(orderDiscount.getId());
                                        discount.setType(orderDiscount.getDiscountType());
                                        discount.setRemark(orderDiscount.getRemark());
                                        discount.setDiscountValue(orderDiscount.getDiscountValue());
                                        discount.setAmount(orderDiscount.getDiscountAmount());
                                        mShoppingCart.addMultyDiscount(mShoppingCart.createNomalDiscount(discount, BillItem.BILL_ITEM_ORDER_SENT_STATUS));
                                    } else if (orderDiscount.getType() == OrderDiscountRequest.MEMBER_DISCOUNT) {
                                        //會員折扣
                                        MemberInfo memberInfo = mDoshokuOrder.getMemberInfo();
                                        if (memberInfo != null) {
                                            mShoppingCart.addMultyDiscount(mShoppingCart.createMemberDiscount(memberInfo, BillItem.BILL_ITEM_ORDER_SENT_STATUS));
                                        }
                                        LoganManager.w_tableMode(TAG, "已下單會員折扣比例=" + memberInfo.getMemberPoint());
                                    } else if (orderDiscount.getType() == OrderDiscountRequest.COUPON_DISCOUNT) {
                                        LoganManager.w_tableMode(TAG, "已下單優惠券折扣金額=" + orderDiscount.getDiscountAmount());
                                        //優惠券折扣
                                        CouponDiscountBean couponDiscount = new CouponDiscountBean();
                                        couponDiscount.setDiscountRecordId(orderDiscount.getId());
                                        couponDiscount.setCouponTypeName1(orderDiscount.getRemark());
                                        couponDiscount.setCouponTypeName2(orderDiscount.getRemark2());
                                        couponDiscount.setCouponTypeName3(orderDiscount.getRemark3());
                                        couponDiscount.setAccumulate(orderDiscount.getAccumulate());
                                        couponDiscount.setSpend(orderDiscount.getSpend());
                                        couponDiscount.setDiscount(orderDiscount.getDiscountValue());
                                        couponDiscount.setAmount(orderDiscount.getDiscountAmount());
                                        mShoppingCart.addMultyDiscount(mShoppingCart.createCouponDiscount(couponDiscount, BillItem.BILL_ITEM_ORDER_SENT_STATUS));
                                    }
                                }
                            }
                        }
                        //打上折上折,免服務費標記
                        setOrderMealPasteDSMark();
                        //計算折扣金額
                        double discountableMoney = getDiscountableAmount();
                        LoganManager.w_tableMode(TAG, "可折扣金額=" + discountableMoney);
                        if (mShoppingCart.getMultyDiscountList().size() > 0) {
                            //調用折扣鏈進行計算
                            totalAmount = MoneyUtil.sub(totalAmount, mShoppingCart.calculateLinkedDiscounts(discountableMoney));
                            LoganManager.w_tableMode(TAG, LoganManager.EVENT_CALCULATE, "賬單後總金額=" + totalAmount);
                        }
                        return totalAmount;
                    }
                })
                /**
                 * 計算賬單小數
                 */
                .map(new Function<Double, Double>() {
                    @Override
                    public Double apply(Double totalAmount) throws Exception {
                        double roundingTotalAmount = getTotalAmountFilterByType(BillItem.ROUNDING_TYPE);
                        if (roundingTotalAmount > 0) {
                            LoganManager.w_tableMode(TAG, "賬單小數=" + roundingTotalAmount);
                            RoundingItem item = new RoundingItem(roundingStr);
                            totalAmount = item.updateBillItem(roundingTotalAmount);
                            if (Double.doubleToLongBits(item.getMoney()) != 0.0) {
                                mBillItemList.add(item);
                                mShoppingCart.setRounding(item.getMoney());
                            }
                        }
                        return totalAmount;
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Double>() {
                    @Override
                    public void accept(Double totalAmount) {
                        //更新總金額
                        mShoppingCart.setTotalAmount(totalAmount);
                        //刷新賬單Item數據
                        mBillItemAdapter.notifyDataSetChanged();
                        //刷新美食Item數據
                        mSelectMealAdapter.notifyDataSetChanged();

                        LoganManager.w_tableMode(TAG, "總金額=" + totalAmount);

                        if (mOrderContentActivity != null) {
                            mOrderContentActivity.initOrderBill(wholeAmount, totalAmount);
                        }
                        if (updateBillInfoEndListener != null) {
                            updateBillInfoEndListener.onUpdateEnd();
                        }
                    }
                });
        addDispose(disposable);
    }

    /**
     * 給不參與折上折，參與免服務費的美食打上標記貼上
     */
    private void setOrderMealPasteDSMark() {
        for (int i = 0; i < mOrderMealList.size(); i++) {
            OrderDetail orderMealItem = mOrderMealList.get(i);
            //初始化標記
            orderMealItem.setAdditionalDiscount((byte) 1);
            orderMealItem.setFreeServiceCharge((byte) 0);
            //查找當前套餐下是否存在折扣
            OrderDetail discountItem = findCurrentMixOrderWithDiscount(orderMealItem);
            if (discountItem != null) {
                Discount discount = discountItem.getDiscount();
                //打上標記
                orderMealItem.setAdditionalDiscount(discount.getAdditionalDiscount());
                orderMealItem.setFreeServiceCharge(discount.getFreeServiceCharge());
            }
        }
    }

    /**
     * 查找當前套餐下折扣
     *
     * @param orderMealItem
     * @return
     */
    private OrderDetail findCurrentMixOrderWithDiscount(OrderDetail orderMealItem) {
        int parentIndex = orderMealItem.getParentIndex();
        int myIndex = orderMealItem.getMyIndex();
        for (OrderDetail orderItem : mOrderMealList) {
            if (orderItem.getType() == DISCOUNT_TYPE && (parentIndex == orderItem.getParentIndex() || myIndex == orderItem.getParentIndex())) {
                //查找到是同組套餐
                return orderItem;
            }
        }
        return null;
    }

    /**
     * 查詢對應的BillItem類
     *
     * @param cla
     * @return
     */
    public BillItem findBillItemByClass(Class<?> cla) {
        BillItem billItem = null;
        for (BillItem item : mBillItemList) {
            if (item.getClass().equals(cla)) {
                billItem = item;
                break;
            }
        }
        return billItem;
    }

    protected void toScanActivity() {
        PermissionUtil.launchCamera(new PermissionUtil.RequestPermission() {

            @Override
            public void onRequestPermissionSuccess() {
                String title = null;
                if (IActivity instanceof MealStandActivity) {
                    title = "掃描會員碼";
                } else if (IActivity instanceof OrderContentActivity) {
                    title = "掃描優惠券碼";
                }
                CC.obtainBuilder(ComponentName.COMPONENT_SCAN)
                        .setActionName("openScanActivity")
                        .addParam("title", title)
                        .build()
                        .callAsyncCallbackOnMainThread((cc, result) -> {


                        });
            }

            @Override
            public void onRequestPermissionFailure(List<String> permissions) {
                DeviceUtils.startSetting(IActivity);
                mRootView.showMessage(LanguageUtils.get_language_system(IActivity, "please.open.camera.permissions", "請前往設置開放照相機權限"));
            }

            @Override
            public void onRequestPermissionFailureWithAskNeverAgain(List<String> permissions) {
                DeviceUtils.startSetting(IActivity);
                mRootView.showMessage(LanguageUtils.get_language_system(IActivity, "please.open.camera.permissions", "請前往設置開放照相機權限"));
            }
        }, new RxPermissions(IActivity), mErrorHandler);
    }

    public void changeNumber(int number) {
        if (!changeNumberCondition(number)) {
            return;
        }
        OrderDetail orderFood = mOrderMealList.get(mSelectMealAdapter.getSelect_full_start_position());
        OrderDetail orderMainFood = mOrderMealList.get(mSelectMealAdapter.getMainStartPos());

        LoganManager.w_tableMode(TAG, LoganManager.EVENT_MODIFY, orderFood.getProductName() + " 數量=" + number);

        mShoppingCart.changeNumber(number, orderFood, orderMainFood,
                mSelectMealAdapter.getSelect_full_start_position(),
                mSelectMealAdapter.getSelect_full_end_position(),
                new ShoppingCartNumberChange.OnNumberChangeListener() {
                    @Override
                    public void achieveMaximum(String name) {
                        String msg = "[" + name + "]" + "已售罄";
                        LoganManager.w_tableMode(TAG, msg);
                        CommonTipDialog.showSurpisedDialog(IActivity, msg, null, null, null, null, null);
                    }
                });
//        if (mMealStandPresenter != null) {
//            mMealStandPresenter.updateMealSoldoutCtrData();
//            mMealStandPresenter.updateOrderFoodNumber();
//        }
        mSelectMealAdapter.notifyDataSetChanged();
        updateBillInfo();
    }

    public boolean changeNumberCondition(int i) {
        if (mOrderMealList.size() <= 0) {
            return false;
        }
        if (mSelectMealAdapter.getSelect_start_position() == -1 || mSelectMealAdapter.getSelect_start_position() >= mSelectMealAdapter.getInfos().size()) {
            return false;
        }
        if (mOrderMealList.get(mSelectMealAdapter.getSelect_start_position()).isIsfood() == false) {
            return false;
        }
        //旧食品不可以修改数量
        if (mDoshokuOrder != null && !mDoshokuOrder.isModifyOrder() && mOrderMealList.get(mSelectMealAdapter.getSelect_start_position()).isNew() == false && i != 0) {
            return false;
        }
        if (mSelectMealAdapter.getSelect_position() == -1) {
            return false;
        }
        if (mOrderMealList.size() <= 0) {
            return false;
        }
        if (mSelectMealAdapter.getMainStartPos() > mOrderMealList.size()) {
            return false;
        }
        OrderDetail orderMainFood = mOrderMealList.get(mSelectMealAdapter.getMainStartPos());
        if (mDoshokuOrder != null && mMealStandPresenter != null && orderMainFood != null) {
            //積分是否滿足
//            if (!mMealStandPresenter.memberPointsCondition(orderMainFood.getPointsRedeem() * i, orderMainFood.getProductName())) {
//                return false;
//            }
        }
        return true;
    }

    /**
     * 送單
     *
     * @param isPrint 是否印單
     */
    public void sendOrder(boolean isPrint, Class<?> afterToActivity) {
        if (!sendOrderConditionFilter()) {
            return;
        }
        if (mDoshokuOrder.getOrderId() < 1) {
            if (getFoodSize() == 0) {
                Class[] parameterTypes = {boolean.class, Class.class};
                Object[] parameters = {isPrint, afterToActivity};
                CommonTipDialog.showDoubtDialog(IActivity, noFoodDeliveryTip, BaseOrderPresenter2.class, this,
                        "executeCreateOrder", parameterTypes, parameters);
            } else {
                executeCreateOrder(isPrint, afterToActivity);
            }
        } else {
            executeAddOrderFood(isPrint, afterToActivity);
        }
    }

    private void executeCreateOrder(boolean isPrint, Class<?> afterToActivity) {
        createOrder(isPrint, afterToActivity);
    }

    private void executeAddOrderFood(boolean isPrint, Class<?> afterToActivity) {
        addOrderFood(isPrint, afterToActivity);
    }

    /**
     * 送單條件過濾
     *
     * @return
     */
    public boolean sendOrderConditionFilter() {
        if (mDoshokuOrder == null) {
            return false;
        }
        MemberInfo memberInfo = mDoshokuOrder.getMemberInfo();
        if (memberInfo == null) {
            for (OrderDetail item : getNewOrderFoodLists()) {
                if (item.getPointsAdd() != 0 || item.getPointsRedeem() != 0) {
                    String msg = "有積分食品,請使用會員后結賬!";
                    CommonTipDialog.showSurpisedDialog(IActivity, msg, BaseOrderPresenter2.class, this,
                            "", null, null);
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 更新食品折扣
     */
    protected void updateFoodDiscount() {

        boolean updateData = false;
        double totalMoney = 0;

        List<OrderDetail> orderDetailList = getOrderFoodLists();
        int start_position = mSelectMealAdapter.getSelect_full_start_position();
        int end_position = mSelectMealAdapter.getSelect_full_end_position();

        boolean hasFoodDiscount = OrderDetail.hasFoodDiscount(orderDetailList, start_position, end_position);
        if (hasFoodDiscount) {
            for (int i = 0; i < orderDetailList.size(); i++) {
                if (start_position <= i && i <= end_position) {
                    OrderDetail orderDetailsBean = orderDetailList.get(i);
                    if (orderDetailsBean.getDiscount() != null && orderDetailsBean.getType() == DISCOUNT_TYPE) {
                        updateData = true;
                        double discountPrice = NomalDiscount.calculationDiscount(orderDetailsBean.getDiscount(), totalMoney);
                        //更新折扣金額
                        orderDetailsBean.setPrice(discountPrice);
                        break;
                    } else {
                        if (!orderDetailsBean.canAbleDiscount()) {
                            //此食品或细项不支持折扣 直接跳过
                            continue;
                        }
                        //保存每個食品套餐折扣總額
                        totalMoney = MoneyUtil.sum(totalMoney, orderDetailsBean.getPrice());
                        //往下找
                        int nextIndex = i + 1;
                        if (orderDetailList.size() == nextIndex || orderDetailList.get(nextIndex).getParentId() == 0) {
                            //已到結尾或者下一個食品是主食品
                            //找到下一個主食品 重置折扣價格
                            totalMoney = 0;
                        }
                        //參與折扣
//                        orderDetailsBean.setAblediscount(1);
                        if (!orderDetailsBean.isNew()) {
                            if (orderDetailsBean.getDiscountStatus() == 0) {
                                //此食品新增折扣
                                orderDetailsBean.setDiscountStatus(1);
                            }
                        }
                    }
                }
            }
        } else {
            for (int i = 0; i < orderDetailList.size(); i++) {
                if (start_position <= i && i <= end_position) {
                    OrderDetail orderDetailsBean = orderDetailList.get(i);
//                    orderDetailsBean.setAblediscount(0);
                    orderDetailsBean.setDiscountStatus(0);
                }
            }
        }
        if (updateData) {
            mSelectMealAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 創建訂單后保存OrderId
     *
     * @param orderId
     */
    protected void setOrderId(double orderId) {
        mDoshokuOrder.setOrderId((long) orderId);
    }

    /**
     * 創建訂單后保存OrderNo
     *
     * @param orderNo
     */
    protected void setOrderNo(String orderNo) {
        mDoshokuOrder.setOrderNo(orderNo);
    }

    /**
     * 重置選中狀態
     */
    public void resetSelected() {
        for (int i = 0; i < mOrderMealList.size(); i++) {
            OrderDetail datasBean = mOrderMealList.get(i);
            datasBean.setSelected(0);
        }
        if (mSelectMealAdapter != null) {
            mSelectMealAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 獲取食品合計
     *
     * @return
     */
    public double getFoodTotal() {
        double total = 0.0;
        for (OrderDetail food : mOrderMealList) {
            if (food.getNumber() == 0) {
                continue;
            }
            if (food.getType() == DISCOUNT_TYPE) {
                //折扣金额直接减掉
                total = MoneyUtil.sub(total, Math.abs(food.getPrice()));
            } else {
                total = MoneyUtil.sum(total, food.getPrice());
            }
        }
        if (total < 0) {
            total = 0;
        }
        return MoneyUtil.get_ItemDecimals_money(total);
    }

    /**
     * 獲取可折扣金額
     *
     * @return
     */
    private double getDiscountableAmount() {
        double total = 0.0;
        int orderSize = mOrderMealList.size();
        for (int i = 0; i < orderSize; i++) {
            OrderDetail orderMealItem = mOrderMealList.get(i);
            if (orderMealItem.getNumber() == 0 || orderMealItem.getAdditionalDiscount() == 0) {
                //不可折上折
                continue;
            }
            if (orderMealItem.getItemType() == 1) {
                if (orderMealItem.canAbleDiscount()) {
                    total = MoneyUtil.sum(total, orderMealItem.getPrice());
                }
            } else {
                int parentIndex = orderMealItem.getParentIndex() - 1;
                OrderDetail parentFood = mOrderMealList.get(parentIndex);
                if (orderSize > parentIndex && parentFood.canAbleDiscount()) {
                    if (orderMealItem.getType() == DISCOUNT_TYPE) {
                        //主食品参与折扣,折扣金额直接减掉
                        total = MoneyUtil.sub(total, Math.abs(orderMealItem.getPrice()));
                    } else {
                        //主食品可參與折扣 子食品才能參與折扣
                        if (orderMealItem.canAbleDiscount()) {
                            total = MoneyUtil.sum(total, orderMealItem.getPrice());
                        }
                    }
                }
            }
        }
        return total;
    }

    /**
     * 獲取可服务费食品合計
     *
     * @return
     */
    private double getServiceableAmout() {
        double total = 0.0;
        int orderSize = mOrderMealList.size();
        for (int i = 0; i < orderSize; i++) {
            OrderDetail orderMealItem = mOrderMealList.get(i);
            if (orderMealItem.getNumber() == 0 || orderMealItem.getFreeServiceCharge() == 1) {
                //免服務費
                continue;
            }
            if (orderMealItem.getItemType() == 1) {
                if (orderMealItem.getScAble() == 1) {
                    total = MoneyUtil.sum(total, orderMealItem.getPrice());
                }
            } else {
                int parentIndex = orderMealItem.getParentIndex() - 1;
                if (orderSize > parentIndex && mOrderMealList.get(parentIndex).getScAble() == 1) {
                    if (orderMealItem.getType() == DISCOUNT_TYPE) {
                        //主食品参与服务费,折扣金额直接减掉
                        total = MoneyUtil.sub(total, Math.abs(orderMealItem.getPrice()));
                    } else {
                        //主食品可參與服务费 子食品才能參與服务费
                        if (orderMealItem.getScAble() == 1) {
                            total = MoneyUtil.sum(total, orderMealItem.getPrice());
                        }
                    }
                }
            }
        }
        if (total < 0) {
            total = 0;
        }
        return MoneyUtil.get_ItemDecimals_money(total);
    }

    /**
     * 獲取總金額
     *
     * @return
     */
    public double getTotalAmountFilterByType(int... filterTypes) {
        double foodTotal = getFoodTotal();
        for (BillItem item : mBillItemList) {
            if (!filterType(item.getType(), filterTypes)) {
                if (item instanceof ServiceChargeItem && mBillItemAdapter.getFreeServiceStauts()) {
                    //TODO 免服務費
                } else {
                    foodTotal = MoneyUtil.sum(foodTotal, item.getMoney());
                    if (0 > foodTotal) {
                        //折扣金額不能超出總額
                        foodTotal = 0;
                    }
                }
            }
        }
        if (foodTotal < 0) {
            foodTotal = 0;
        }
        return MoneyUtil.get_ItemDecimals_money(foodTotal);
    }

    private boolean filterType(int curType, int... filterTypes) {
        for (int type : filterTypes) {
            if (curType == type) {
                return true;
            }
        }
        return false;
    }

    /**
     * 獲取總金額:已減去折扣,服務費
     *
     * @return
     */
    public double getTotalAmount() {
        double foodTotal = getFoodTotal();
        for (BillItem item : mBillItemList) {
            if (item instanceof ServiceChargeItem && mBillItemAdapter.getFreeServiceStauts()) {
                //TODO 免服務費
            } else {
                foodTotal = MoneyUtil.sum(foodTotal, item.getMoney());
                if (0 > foodTotal) {
                    //折扣金額不能超出總額
                    foodTotal = 0;
                }
            }
        }
        if (foodTotal < 0) {
            foodTotal = 0;
        }
        return MoneyUtil.get_ItemDecimals_money(foodTotal);
    }

    /**
     * 獲取賬單小數
     *
     * @return
     */
    protected Double getRounding() {
        for (BillItem item : mBillItemList) {
            if (item instanceof RoundingItem) {
                return item.getMoney();
            }
        }
        return null;
    }

    /**
     * 獲取食品總數量
     *
     * @return
     */
    public int getFoodCount() {
        int count = 0;
        for (OrderDetail food : mOrderMealList) {
            if (food.getType() != DISCOUNT_TYPE) {
                //排除掉折扣
                count += food.getNumber();
            }
        }
        return count;
    }

    /**
     * 獲取食品Item個數
     *
     * @return
     */
    public int getFoodSize() {
        return getOrderFoodLists().size();
    }

    /**
     * 返回選中已送單食品ID
     *
     * @return
     */
    protected String getSelectedOldFoodIds() {
        StringBuilder builder = new StringBuilder();
        List<OrderDetail> orderDetails = getOldOrderFoodLists();
        for (int i = orderDetails.size() - 1; i >= 0; i--) {
            OrderDetail orderDetail1 = orderDetails.get(i);
            if (orderDetail1.getSelected() != 0 && orderDetail1.getType() != DISCOUNT_TYPE) {
                builder.append(orderDetail1.getId());
                builder.append(",");
            }
        }
        String str = builder.toString();
        if (str.endsWith(",")) {
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }


    /**
     * 返回選中已送單食品
     *
     * @return
     */
    protected List<OrderDetail> getSelectedOldFood() {
        List<OrderDetail> selectedOldOrders = new ArrayList<>();
        List<OrderDetail> oldOrders = getOldOrderFoodLists();
        int start_position = mSelectMealAdapter.getSelect_full_start_position();
        int end_position = mSelectMealAdapter.getSelect_full_end_position();
        for (int i = oldOrders.size() - 1; i >= 0; i--) {
            if (start_position <= i && i <= end_position) {
                OrderDetail orderDetail1 = oldOrders.get(i);
                if (orderDetail1.getType() != DISCOUNT_TYPE) {
                    selectedOldOrders.add(orderDetail1);
                }
            }
        }
        return selectedOldOrders;
    }

    /**
     * 返回選中已送單食品、折扣
     *
     * @return
     */
    protected List<OrderDetail> getSelectedOldFoodAndDiscount() {
        List<OrderDetail> selectedOldOrders = new ArrayList<>();
        List<OrderDetail> oldOrders = getOldOrderFoodLists();
        int start_position = mSelectMealAdapter.getSelect_full_start_position();
        int end_position = mSelectMealAdapter.getSelect_full_end_position();
        for (int i = oldOrders.size() - 1; i >= 0; i--) {
            if (start_position <= i && i <= end_position) {
                OrderDetail orderDetail1 = oldOrders.get(i);
                selectedOldOrders.add(orderDetail1);
            }
        }
        return selectedOldOrders;
    }

    protected CreateOrderRequest getCreateOrderRequest(List<OrderDetail> foodList) {
        List<OrderDetail> newFoodList = OrderDetail.transNewOrderDetails(foodList);
        if (RestaurantExpandInfoUtils.getValue(ExpandConstant.MergeSendFood, true)) {
            //合并未送单主食品
            mergeMainFoodNumber(newFoodList);
        }

        setChildScAbleByMainAble(newFoodList);
        setChildDiscountByMainAblediscount(newFoodList);

        TableBean.DataBean tableBean = mDoshokuOrder.getOpenTableInfo();

        int restaurantId = RestaurantInfoManager.newInstance().getRestaurantId();
        CreateOrderRequest request = new CreateOrderRequest();
        request.setTableNumber(tableBean.getTableNumber());
        request.setOrderDetails(orderDetailBeanToFoodRequest(newFoodList));
        request.setPerson(tableBean.getPerson());
        request.setTableId(tableBean.getId());
        request.setTableName(tableBean.getTableName());
        request.setScanId(tableBean.getScanId());
        request.setRounding(getRounding());
        request.setRestaurantId(restaurantId);

        List<OrderDiscountRequest> discountDetails = getOrderDiscountDetails();
        request.setDiscountDetails(discountDetails);
        return request;
    }


    protected AddOrderRequest getAddOrderRequest(List<OrderDetail> foodList) {
        List<OrderDetail> newFoodList = OrderDetail.transNewOrderDetails(foodList);
        if (RestaurantExpandInfoUtils.getValue(ExpandConstant.MergeSendFood, true)) {
            //合并未送单主食品
            mergeMainFoodNumber(newFoodList);
        }

        setChildScAbleByMainAble(newFoodList);
        setChildDiscountByMainAblediscount(newFoodList);

        AddOrderRequest request = new AddOrderRequest();
        request.setOrderId(mDoshokuOrder.getOrderId());
        request.setTableId(mDoshokuOrder.getOpenTableInfo().getId());
        if (mDoshokuOrder.getMemberInfo() != null) {
            request.setMemberId(mDoshokuOrder.getMemberInfo().getId());
        }
        request.setTableNumber(mDoshokuOrder.getOpenTableInfo().getTableNumber());
        request.setMaps(orderDetailBeanToAddFoodRequest(newFoodList));
        if (mDoshokuOrder.getDeleteMealOrders() != null) {
            request.setDeleteOrders(mDoshokuOrder.getDeleteMealOrders());
        }
        if (mDoshokuOrder.getDeleteDiscountIds() != null) {
            request.setDeleteDiscountIds(mDoshokuOrder.getDeleteDiscountIds());
        }
        Double rounding = getRounding();
        request.setRounding(rounding != null ? rounding : 0);

        List<OrderDiscountRequest> discountDetails = getOrderDiscountDetails();
        request.setDiscountDetails(discountDetails);
        return request;
    }

    /**
     * 獲取賬單折扣
     *
     * @return
     */
    private List<OrderDiscountRequest> getOrderDiscountDetails() {
        List<OrderDiscountRequest> discountRequests = new ArrayList<>();
        for (BillItem item : mBillItemList) {
            if (item instanceof DiscountItem) {
                if (item.getType() == BillItem.NOMAL_DISCOUNT_TYPE) {
                    discountRequests.add(OrderDiscountRequest.orderDiscountTransRequest((DiscountItem) item));
                    continue;
                }
                if (item.getType() == BillItem.MEMBER_DISCOUNT_TYPE) {
                    discountRequests.add(OrderDiscountRequest.memberDiscountTransRequest((DiscountItem) item));
                    continue;
                }
                if (item.getType() == BillItem.COUPON_DISCOUNT_TYPE) {
                    discountRequests.add(OrderDiscountRequest.couponDiscountTransRequest((DiscountItem) item));
                    continue;
                }
            }
        }
        return discountRequests;
    }

    protected Map<String, List<OrderResponse.OrderDetailsBean>> orderDetailBeanToFoodRequest(List<OrderDetail> foodList) {
        Map<String, List<OrderResponse.OrderDetailsBean>> orderDetails = new HashMap<>();
        if (foodList != null) {
            //套餐明細ID
            long mapIndex = 0;
            //打印用到，清理掉之前保存的食品
            mDoshokuOrder.getNewFoodList().clear();
            for (int i = 0; i < foodList.size(); i++) {
                OrderDetail item = foodList.get(i);
                if (item.getItemType() != 1) {
                    //不是主食品直接跳過
                    continue;
                }
                mapIndex += 1;
                List<OrderResponse.OrderDetailsBean> orderItems = getOrderMapItems(1, i, item, foodList);
                if (orderItems.size() > 0) {
                    orderDetails.put(String.valueOf(mapIndex), orderItems);
                }
            }
        }
        return orderDetails;
    }

    protected Map<String, List<OrderResponse.OrderDetailsBean>> orderDetailBeanToAddFoodRequest(List<OrderDetail> foodList) {
        /**
         * 1#主食品（完全新點）
         * 2#主食品+子食品+細項（主食品基礎上新加）
         */
        long type1 = 1;
        long type2 = 2;
        //打印用到，清理掉之前保存的食品
        mDoshokuOrder.getNewFoodList().clear();
        //可重複的map
        Map<String, List<OrderResponse.OrderDetailsBean>> orderDetails = new HashMap<>();
        if (foodList != null) {
            //套餐明細ID
            String mapIndex;
            int indexCount = 0;
            for (int i = 0; i < foodList.size(); i++) {
                OrderDetail item = foodList.get(i);
                if (item.getItemType() != 1) {
                    //不是主食品直接跳過
                    continue;
                }
                indexCount += 1;
                if (item.isNew()) {
                    //完全新點的一個食品
                    mapIndex = indexCount + "-" + type1;
                } else {
                    //基礎上新加
                    mapIndex = indexCount + "-" + type2;
                }
                List<OrderResponse.OrderDetailsBean> orderItems = getOrderMapItems(2, i, item, foodList);
                if (orderItems.size() > 0) {
                    orderDetails.put(mapIndex, orderItems);
                }
            }
        }
        return orderDetails;
    }

    private List<OrderResponse.OrderDetailsBean> getOrderMapItems(int orderAction, int startIndex, OrderDetail parentItem, List<OrderDetail> foodList) {
        List<OrderResponse.OrderDetailsBean> orderItems = new ArrayList<>();
        for (int j = startIndex; j < foodList.size(); j++) {
            OrderDetail item = foodList.get(j);
            boolean myIndex = item.getMyIndex() != parentItem.getMyIndex();
            boolean parentIndex = item.getParentIndex() != parentItem.getMyIndex();
            if (myIndex && parentIndex && item.getType() != OrderDetail.MODIFIER_TYPE) {
                //已經循環過當前套餐 退出循環
                break;
            }
            if (item.getType() == DISCOUNT_TYPE) {
                //折扣直接跳過
                continue;
            }

            OrderResponse.OrderDetailsBean orderItem = new OrderResponse.OrderDetailsBean();
            if (orderAction == 2) {
                orderItem.setOrderId(item.getOrderId());
                if (item.getId() != 0) {
                    orderItem.setId(item.getId());
                }
            }
            orderItem.setMemberId(UserContext.newInstance().getMemberId());
            orderItem.setProductName(item.getProductName());
            orderItem.setProductId(item.getProductId());
            orderItem.setParentId(item.getParentId());
            orderItem.setTopId(item.getTopId());
            orderItem.setNumber(item.getNumber());
            orderItem.setPrice(item.getUnit_price());
            orderItem.setCost(item.getCost());
            orderItem.setType(item.getType());
            orderItem.setPrintSetIng(item.getPrintseting());
            orderItem.setAblediscount(item.getAblediscount());
            orderItem.setScAble(item.getScAble());
            if (item.canAbleDiscount()) {
                //可參與折扣
                List<OrderResponse.OrderDetailsBean.RestaurantDiscountVO> discountList = getRestaurantDiscountList(foodList, parentItem);
                if (discountList.size() > 0) {
                    orderItem.setDiscountList(discountList);
                }
            }
//            orderItem.setLunchboxPrice(0);
            orderItem.setPointsAdd(item.getPointsAdd());
            orderItem.setPointsRedeem(item.getPointsRedeem());

            if (orderAction == 2) {
                if (item.isNew() || item.getDiscountStatus() == 1) {
                    //這裡只添加新食品或有新折扣食品
                    orderItems.add(orderItem);
                    //保存新食品，打印用到
                    mDoshokuOrder.getNewFoodList().add(item);
                }
            } else {
                if (item.isNew()) {
                    //這裡只添加新食品
                    orderItems.add(orderItem);
                    //保存新食品，打印用到
                    mDoshokuOrder.getNewFoodList().add(item);
                }
            }
        }
        return orderItems;
    }

    /**
     * 送单前根据主食品Ablediscount更新子食品Ablediscount（前端处理后台直接存即可）
     *
     * @param newFoodList
     */
    private void setChildDiscountByMainAblediscount(List<OrderDetail> newFoodList) {
        int orderSize = newFoodList.size();
        for (int i = 0; i < orderSize; i++) {
            OrderDetail food = newFoodList.get(i);
            if (food.getItemType() != 1) {
                int parentIndex = food.getParentIndex() - 1;
                if (orderSize > parentIndex && !newFoodList.get(parentIndex).canAbleDiscount()) {
                    //主食品不可參與折扣 子食品也不能參與折扣
                    food.setAblediscount(0);
                }
            }
        }
    }

    /**
     * 送单前根据主食品ScAble更新子食品ScAble（前端处理后台直接存即可）
     *
     * @param newFoodList
     */
    private void setChildScAbleByMainAble(List<OrderDetail> newFoodList) {
        int orderSize = newFoodList.size();
        for (int i = 0; i < orderSize; i++) {
            OrderDetail food = newFoodList.get(i);
            if (food.getItemType() != 1) {
                int parentIndex = food.getParentIndex() - 1;
                if (orderSize > parentIndex && !newFoodList.get(parentIndex).canAbleDiscount()) {
                    //主食品不可參與折扣 子食品也不能參與折扣
                    food.setScAble((byte) 0);
                }
            }
        }
    }

    /**
     * 合并新下单主食品数量
     *
     * @param foodList
     */
    protected void mergeMainFoodNumber(List<OrderDetail> foodList) {
        List<Integer> removeIndexs = new ArrayList<>();
        for (int i = 0; i < foodList.size(); i++) {
            OrderDetail orderFood = foodList.get(i);
            if (!orderFood.isNew() || orderFood.getItemType() != 1) {
                continue;
            }
            if (hasChildFood(foodList, orderFood)) {
                continue;
            }
            //合并总数量
            int mergeNum = orderFood.getNumber();
            for (int j = i; j < foodList.size(); j++) {
                if (!orderFood.isNew() || i == j) {
                    continue;
                }
                OrderDetail mergeFood = foodList.get(j);
                boolean canMerge = mergeFood.getItemType() == 1 && mergeFood.getProductId() == orderFood.getProductId() && !hasChildFood(foodList, mergeFood);
                if (canMerge) {
                    //合并数量
                    mergeNum += mergeFood.getNumber();
                    if (!removeIndexs.contains(mergeFood.getMyIndex())) {
                        //添加所需移除已合并的食品
                        removeIndexs.add(mergeFood.getMyIndex());
                    }
                }
            }
            orderFood.setNumber(mergeNum);
        }

        for (int i = removeIndexs.size() - 1; i >= 0; i--) {
            for (int j = foodList.size() - 1; j >= 0; j--) {
                if (removeIndexs.get(i) == foodList.get(j).getMyIndex()) {
                    foodList.remove(j);
                    break;
                }
            }
        }
    }

    /**
     * 是否包含子项
     *
     * @param orderDetailList
     * @param orderDetail
     * @return
     */
    private boolean hasChildFood(List<OrderDetail> orderDetailList, OrderDetail orderDetail) {
        List<OrderDetail> orderList = getChildFoods(orderDetailList, orderDetail);
        if (orderList.size() == 0) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 獲取食品下所有子項
     *
     * @param orderDetailList
     * @param orderDetail
     * @return
     */
    protected List<OrderDetail> getChildFoods(List<OrderDetail> orderDetailList, OrderDetail orderDetail) {
        List<OrderDetail> orderList = new ArrayList<>();
        if (orderDetail.getItemType() == 3) {
            return orderList;
        }
        for (int i = 0; i < orderDetailList.size(); i++) {
            if (orderDetailList.get(i).getParentIndex() == orderDetail.getMyIndex()) {
                orderList.add(orderDetailList.get(i));
            }
        }
        return orderList;
    }

    /**
     * 根據主食品ID獲取折扣列表
     *
     * @param orderItems
     * @param parentItem
     * @return
     */
    private List<OrderResponse.OrderDetailsBean.RestaurantDiscountVO> getRestaurantDiscountList(List<OrderDetail> orderItems, OrderDetail parentItem) {
        long mainParentId = parentItem.isNew() ? parentItem.getProductId() : parentItem.getId();
        List<OrderResponse.OrderDetailsBean.RestaurantDiscountVO> discountList = new ArrayList<>();
        for (OrderDetail item : orderItems) {
            if (item.getDiscount() != null && item.getParentId() == mainParentId) {
                Discount discount = item.getDiscount();
                OrderResponse.OrderDetailsBean.RestaurantDiscountVO discountVO = new OrderResponse.OrderDetailsBean.RestaurantDiscountVO();
                discountVO.setId(discount.getDiscountRecordId());
                discountVO.setDiscountId(discount.getId());
                discountVO.setType(discount.getType());
                discountVO.setRemark(discount.getRemark());
                discountVO.setDiscountValue(discount.getDiscountValue());
                discountVO.setDiscountAmount(item.getPrice());
                discountList.add(discountVO);
                if (item.isNew()) {
                    //设置当前食品下包含为送单折扣状态
                    parentItem.setDiscountStatus(1);
                }
            }
        }
        return discountList;
    }

    /**
     * 獲取優惠券折扣ID
     *
     * @return
     */
    protected Long getCouponDiscountId() {
        MemberCouponDiscount couponDiscount = (MemberCouponDiscount) mShoppingCart.getDiscountByType(BillItem.COUPON_DISCOUNT_TYPE);
        if (couponDiscount != null) {
            return couponDiscount.getCouponDiscountId();
        }
        return null;
    }

    /**
     * 返回未送單整單折扣
     *
     * @return
     */
    protected BillItem getNewDiscount() {
        for (BillItem item : mBillItemList) {
            if (item.getStatus() == BillItem.BILL_ITEM_NO_ORDER_STATUS &&
                    (item.getType() == BillItem.NOMAL_DISCOUNT_TYPE ||
                            item.getType() == BillItem.MEMBER_DISCOUNT_TYPE ||
                            item.getType() == BillItem.COUPON_DISCOUNT_TYPE)) {
                return item;
            }
        }
        return null;
    }

    /**
     * 返回未送單食品列表
     *
     * @return
     */
    protected List<OrderDetail> getNewOrderFoodLists() {
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (int i = 0; i < getOrderFoodLists().size(); i++) {
            OrderDetail orderDetail = getOrderFoodLists().get(i);
            if (orderDetail.isNew()) {
                orderDetails.add(orderDetail);
            }
        }
        return orderDetails;
    }

    /**
     * 返回已送單食品列表
     *
     * @return
     */
    protected List<OrderDetail> getOldOrderFoodLists() {
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (int i = 0; i < getOrderFoodLists().size(); i++) {
            OrderDetail orderDetail = getOrderFoodLists().get(i);
            if (!orderDetail.isNew()) {
                orderDetails.add(orderDetail);
            }
        }
        return orderDetails;
    }


    public boolean hasNesOrderFoods() {
        if (getNewOrderFoodLists().size() > 0) {
            return true;
        }
        return false;
    }

    protected boolean hasOldOrderFoods() {
        if (getOldOrderFoodLists().size() > 0) {
            return true;
        }
        return false;
    }

    public List<OrderDetail> getOrderFoodLists() {
        return mOrderMealList;
    }

    /**
     * 修改訂單
     *
     * @param //orderId 訂單號
     * @param //person  人數
     */
    public void updateOrderPerson(String peopleNumber, TextView textView) {
        RequestBody requestBody = new FormBody.Builder()
                .add("orderId", String.valueOf(mDoshokuOrder.getOrderId()))
                .add("person", String.valueOf(peopleNumber))
                .build();
        mModel.updateOrder(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(BaseResult baseResult) {
                        if (baseResult.isSuccess()) {
                            if (mOrderContentActivity != null) {
                                textView.setText(peopleNumber);
                            } else {
                                textView.setText("人數:" + peopleNumber);
                            }
                            mDoshokuOrder.getOpenTableInfo().setPerson(Integer.parseInt(peopleNumber));
                        }
                    }
                });
    }

    public ShoppingCart getShoppingCart() {
        return mShoppingCart;
    }

    public SelectMealAdapter2 getSelectMealAdapter(){
        return mSelectMealAdapter;
    }

    public interface UpdateBillInfoEndListener {
        void onUpdateEnd();
    }
}

