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

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

import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.base.common.bean.MemberInfo;
import com.gingersoft.gsa.cloud.base.order.bean.BillOrderMoney;
import com.gingersoft.gsa.cloud.base.order.bean.OrderBean;
import com.gingersoft.gsa.cloud.base.order.bean.OrderDetail;
import com.gingersoft.gsa.cloud.base.order.bean.discount.CouponDiscountBean;
import com.gingersoft.gsa.cloud.base.order.bean.discount.OrderDiscount;
import com.gingersoft.gsa.cloud.base.order.bean.mealManger.MyOrderManage;
import com.gingersoft.gsa.cloud.base.order.bean.mealManger.OpenTableManage;
import com.gingersoft.gsa.cloud.base.table.bean.TableBean;
import com.gingersoft.gsa.cloud.base.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.bean.R;
import com.gingersoft.gsa.cloud.bean.mvp.contract.BaseOrderContract;
import com.gingersoft.gsa.cloud.bean.mvp.model.bean.request.AddOrderRequest;
import com.gingersoft.gsa.cloud.bean.mvp.model.bean.request.CreateOrderRequest;
import com.gingersoft.gsa.cloud.bean.mvp.ui.activity.MealStandActivity;
import com.gingersoft.gsa.cloud.bean.mvp.ui.activity.OrderContentActivity;
import com.gingersoft.gsa.cloud.bean.mvp.ui.adapter.OrderMoneyAdapter;
import com.gingersoft.gsa.cloud.bean.mvp.ui.adapter.meal.SelectMealAdapter;
import com.gingersoft.gsa.cloud.database.bean.Discount;
import com.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
import com.gingersoft.gsa.cloud.zxing.MipcaCaptureActivity;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
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.android.schedulers.AndroidSchedulers;
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.base.order.bean.OrderDetail.DISCOUNT_TYPE;


/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2020-01-11
 * 修订历史：2020-01-11
 * 描述：
 */
@ActivityScope
public abstract class BaseOrderPresenter<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 BaseOrderPresenter mBaseOrderPresenter;
    private Activity IActivity;
    private OrderContentActivity mOrderContentActivity;
    private MealStandPresenter mMealStandPresenter;

    //订单数据管理类
    protected MyOrderManage myOrderManage;
    protected OpenTableManage openTableManage;

    //訂單食品適配器
    protected SelectMealAdapter mSelectMealAdapter;
    protected List<OrderDetail> mOrderFoodList;

    //整單相關金額適配器
    protected OrderMoneyAdapter mOrderMoneyAdapter;
    protected List<BillOrderMoney> mOrderMoneyList;

    protected OrderDetail mCurrentOrderDetailBean;
    //選中操作的食品下標
    protected int orderSelectPosition = -1;

    //币種
    public String cashStr = "$";
    public String serviceChargeStr = "服務費";
    private final String noFoodDeliveryTip = "賬單沒有食品，是否開台?";


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

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

    void saveCreateTime(long createTime) {
        if (OpenTableManage.getDefault().getTableBean() == null) {
            OpenTableManage.getDefault().setTableBean(new TableBean.DataBean());
        }
        OpenTableManage.getDefault().getTableBean().setCreateTime(TimeUtils.getTime(createTime, TimeUtils.DEFAULT_DATE_FORMAT));
    }


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

        this.IActivity = (Activity) mRootView;
        this.openTableManage = OpenTableManage.getDefault();
        this.myOrderManage = MyOrderManage.getInstance();
        this.mOrderFoodList = myOrderManage.getOrderFoodList();
        this.mOrderMoneyList = myOrderManage.getOrderMoneyList();

        if (IActivity instanceof OrderContentActivity) {
            mOrderContentActivity = (OrderContentActivity) IActivity;
        }
        if (this instanceof MealStandPresenter) {
            mMealStandPresenter = (MealStandPresenter) this;
        }

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

        if (!containsTableService()) {
            addTableServiceAmount();
        }
        if (this instanceof MealStandPresenter) {
            addSentOrderDiscount();
            addOrderRounding();
            //設置賬單總金額
            myOrderManage.setTotalAmount(getTotalAmount());
        } else {
            updateBillOrderItem();
        }
    }

    private boolean containsTableService() {
        for (int i = mOrderMoneyList.size() - 1; i >= 0; i--) {
            BillOrderMoney billOrderMoney = mOrderMoneyList.get(i);
            if (billOrderMoney.getType() == BillOrderMoney.SERVERCHARGE_TYPE) {
                return true;
            }
        }
        return false;
    }

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

    private void initOrderAdapter() {
        if (mSelectMealAdapter == null) {
            mSelectMealAdapter = new SelectMealAdapter(IActivity, mOrderFoodList, this);
            //設置子父級下標
            mSelectMealAdapter.setIndex();
        }
        if (mOrderMoneyAdapter == null) {
            mOrderMoneyAdapter = new OrderMoneyAdapter(IActivity, mOrderMoneyList, cashStr);
        }
    }

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

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

            @Override
            public void onMealCountDelete(OrderDetail datasBean, int position) {
                mRootView.recordOperat(true);
                if (datasBean.getNumber() == 1) {
                    mSelectMealAdapter.removeFoodItem();
                } else {
                    changeNumber(datasBean.getNumber() - 1);
                }
                mSelectMealAdapter.notifyDataSetChanged();
                if (mOrderContentActivity != null) {
                    mOrderContentActivity.initOrderDetail();
                }
                //更新折扣
                updateBillOrderItem();
            }

            @Override
            public void onMealCountAdd(OrderDetail datasBean, int position) {
                mRootView.recordOperat(true);
                changeNumber(datasBean.getNumber() + 1);
                if (mOrderContentActivity != null) {
                    mOrderContentActivity.initOrderDetail();
                }
                //更新折扣
                updateBillOrderItem();
            }

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

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

            @Override
            public void onRequestPermissionSuccess() {
                if (IActivity instanceof MealStandActivity) {
                    MipcaCaptureActivity.startMipcaCaptureActivity(IActivity, "掃描會員碼");
                } else if (IActivity instanceof OrderContentActivity) {
                    MipcaCaptureActivity.startMipcaCaptureActivity(IActivity, "掃描優惠券碼");
                }
            }

            @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;
        }
        myOrderManage.changeNumber(number);
        if (mMealStandPresenter != null) {
            mMealStandPresenter.updateMealSoldoutCtrData();
            mMealStandPresenter.updateOrderFoodNumber();
        }
        updateBillOrderItem();
        mSelectMealAdapter.notifyDataSetChanged();
    }

    public boolean changeNumberCondition(int i) {
        if (MyOrderManage.getInstance().getSize() <= 0) {
            return false;
        }
        if (mSelectMealAdapter.getSelect_start_position() == -1 || mSelectMealAdapter.getSelect_start_position() >= mSelectMealAdapter.getInfos().size()) {
            return false;
        }
        if (myOrderManage.getOrderFoodList().get(mSelectMealAdapter.getSelect_start_position()).isIsfood() == false) {
            return false;
        }
        //旧食品不可以修改数量
        if (!myOrderManage.isModifyOrder() && myOrderManage.getOrderFoodList().get(mSelectMealAdapter.getSelect_start_position()).isNew() == false && i != 0) {
            return false;
        }
        if (mSelectMealAdapter.getSelect_position() == -1) {
            return false;
        }
        if (myOrderManage.getOrderFoodList().size() <= 0) {
            return false;
        }
        if (myOrderManage.getSelmainstartpositon() > myOrderManage.getOrderFoodList().size()) {
            return false;
        }
        OrderDetail orderMainFood = myOrderManage.getOrderFoodList().get(myOrderManage.getSelmainstartpositon());
        if (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 (MyOrderManage.getInstance().getOrderId() < 1) {
            if (getFoodSize() == 0) {
                Class[] parameterTypes = {boolean.class, Class.class};
                Object[] parameters = {isPrint, afterToActivity};
                CommonTipDialog.showDoubtDialog(IActivity, noFoodDeliveryTip, BaseOrderPresenter.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() {
        MemberInfo memberInfo = MyOrderManage.getInstance().getMemberInfo();
        if (memberInfo == null) {
            for (OrderDetail item : getNewOrderFoodLists()) {
                if (item.getPointsAdd() != 0 || item.getPointsRedeem() != 0) {
                    String msg = "有積分食品,請使用會員后結賬!";
                    CommonTipDialog.showSurpisedDialog(IActivity, msg, BaseOrderPresenter.class, this,
                            "", null, null);
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 更新賬單金額
     */
    public void updateBillOrderItem() {
        if (!containsTableService()) {
            addTableServiceAmount();
        }
        updateFoodDiscount();
        updateTableServiceAmount();
        updateOrderDiscount();
        updateMemberDiscount();
        updateMemberCoupon();
        updateOrderRounding();
        myOrderManage.setTotalAmount(getTotalAmount());
    }

    /**
     * 添加已送單折扣
     */
//    private void addSentOrderDiscount() {
//        OrderBean orderBean = myOrderManage.getOrderBean();
//        if (orderBean != null) {
//            DiscountResult discountResult = orderBean.getDiscountDetail();
//            if (discountResult != null) {
//                Discount discount = discountResult.getDiscount();
//                MemberInfo memberDiscount = discountResult.getMemberDiscount();
//                CouponDiscountBean memberCoupon = discountResult.getMemberCoupon();
//                if (memberDiscount != null) {
//                    //整單折扣
//                    if (discount.getDiscount_value() != 0) {
//                        //百分比折扣
//                        discount.setType(1);
//                        addOrderDiscount(true, discount, BillOrderMoney.BILL_ITEM_ORDER_SENT_STATUS);
//                    } else {
//                        //金額折扣
//                        discount.setType(0);
//                        addOrderDiscount(true, discount, BillOrderMoney.BILL_ITEM_ORDER_SENT_STATUS);
//                    }
//                }
//                if (memberCoupon != null) {
//                    //會員優惠券
//                    if (memberDiscount != null) {
//                        addMemberCoupon(memberCoupon, memberDiscount.getId(), BillOrderMoney.BILL_ITEM_ORDER_SENT_STATUS);
//                    }
//                }
//                if (memberDiscount != null) {
//                    //會員折扣
//                    addMemberDiscount(memberDiscount.getId(), memberDiscount.getMemberDiscount(), memberDiscount.getMemberName(), memberDiscount.getLevelName1(), BillOrderMoney.BILL_ITEM_ORDER_SENT_STATUS);
//                }
//            }
//        }
//    }
    protected void addSentOrderDiscount() {
        OrderBean orderBean = myOrderManage.getOrderBean();
        if (orderBean != null) {
            List<OrderDiscount.Respose> discountDetails = orderBean.getDiscountDetails();
            if (discountDetails != null) {
                for (int i = 0; i < discountDetails.size(); i++) {
                    OrderDiscount.Respose orderDiscount = discountDetails.get(i);
                    if (orderDiscount.getType() == OrderDiscount.ORDER_DISCOUNT) {
                        //整單折扣
                        Discount discount = new Discount();
                        discount.setId(orderDiscount.getDiscountId());
                        discount.setRemark(orderDiscount.getRemark());
                        if (orderDiscount.getDiscountValue() != 0) {
                            //百分比折扣
                            discount.setType(1);
                            discount.setDiscount_value(orderDiscount.getDiscountValue());
                            addOrderDiscount(true, discount, BillOrderMoney.BILL_ITEM_ORDER_SENT_STATUS);
                            continue;
                        }
                        if (orderDiscount.getDiscountAmount() != 0) {
                            //金額折扣
                            discount.setType(0);
                            discount.setAmount(orderDiscount.getDiscountAmount());
                            addOrderDiscount(true, discount, BillOrderMoney.BILL_ITEM_ORDER_SENT_STATUS);
                            continue;
                        }
                    } else if (orderDiscount.getType() == OrderDiscount.MEMBER_DISCOUNT) {
                        //會員折扣
                        MemberInfo memberInfo = myOrderManage.getMemberInfo();
                        if (memberInfo != null) {
                            addMemberDiscount(memberInfo.getId(), orderDiscount.getDiscountValue(), memberInfo.getMemberName(), memberInfo.getLevelName1(), BillOrderMoney.BILL_ITEM_ORDER_SENT_STATUS);
                        }
                    } else if (orderDiscount.getType() == OrderDiscount.COUPON_DISCOUNT) {
                        CouponDiscountBean couponDiscount = new CouponDiscountBean();
                        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());

                        MemberInfo memberInfo = myOrderManage.getMemberInfo();
                        if (memberInfo != null) {
                            addCouponDiscount(couponDiscount, myOrderManage.getMemberInfo().getId(), BillOrderMoney.BILL_ITEM_ORDER_SENT_STATUS);
                        }
                    }
                }
            }
        }
    }

    /**
     * 添加餐檯服務費
     */
    protected void addTableServiceAmount() {
        TableBean.DataBean dataBean = OpenTableManage.getDefault().getTableBean();
        if (dataBean == null) {
            return;
        }
        double serviceAmount = MoneyUtil.divide(MoneyUtil.multiply(getScAbleFoodTotal(), dataBean.getServiceCharge()).doubleValue(), 100, MoneyUtil.ItemDecimals);
        if (serviceAmount > 0) {
            BillOrderMoney orderMoney = new BillOrderMoney();
            orderMoney.setMoney(MoneyUtil.get_ItemDecimals_money(serviceAmount));
            orderMoney.setTitle(dataBean.getServiceCharge() + "%" + serviceChargeStr);
            orderMoney.setStatus(BillOrderMoney.BILL_ITEM_ORDER_SENT_STATUS);
            orderMoney.setType(BillOrderMoney.SERVERCHARGE_TYPE);
            orderMoney.setTextColor(ArmsUtils.getColor(IActivity, R.color.theme_black));
            BillOrderMoney discountBill = getBillOrderItemByType(BillOrderMoney.ORDER_DISCOUNT_TYPE);
            if (discountBill != null) {
                mOrderMoneyList.add(0, orderMoney);
            } else {
                mOrderMoneyList.add(orderMoney);
            }
            mOrderMoneyAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 更新服务费
     */
    private void updateTableServiceAmount() {
        BillOrderMoney billOrderMoney = getBillOrderItemByType(BillOrderMoney.SERVERCHARGE_TYPE);
        if (billOrderMoney != null) {
            TableBean.DataBean dataBean = OpenTableManage.getDefault().getTableBean();
//            double serviceAmount = getTotalAmountFilterByType(BillOrderMoney.SERVERCHARGE_TYPE, BillOrderMoney.DISCOUNT_TYPE, BillOrderMoney.ROUNDING_TYPE) * dataBean.getServiceCharge() / 100;
            double serviceAmount = getScAbleFoodTotal() * dataBean.getServiceCharge() / 100;
            if (serviceAmount > 0) {
                billOrderMoney.setMoney(MoneyUtil.get_ItemDecimals_money(serviceAmount));
            } else {
                mOrderMoneyList.remove(billOrderMoney);
            }
            mOrderMoneyAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 添加賬單折扣
     *
     * @param discount
     */
    protected void addOrderDiscount(boolean init, Discount discount, int status) {

        removeBillOrderItemByType(BillOrderMoney.ORDER_DISCOUNT_TYPE);

        double totalMoney = getDiscountableFoodTotal(BillOrderMoney.ORDER_DISCOUNT_TYPE, true);
        double discountPrice = Discount.calculationDiscount(discount, totalMoney);
        BillOrderMoney orderMoney = new BillOrderMoney();
        orderMoney.setMoney(discountPrice);
        orderMoney.setTitle(discount.getRemark());
        orderMoney.setType(BillOrderMoney.ORDER_DISCOUNT_TYPE);
        if (status == 0) {
            orderMoney.setTextColor(ArmsUtils.getColor(IActivity, R.color.theme_hint_color));
        } else {
            orderMoney.setTextColor(ArmsUtils.getColor(IActivity, R.color.theme_black));
        }
        orderMoney.setStatus(status);
        orderMoney.setDiscount(discount);

        mOrderMoneyList.add(orderMoney);
        mOrderMoneyAdapter.notifyDataSetChanged();

        //更新總金額
        if (!init && mOrderContentActivity != null) {
            //先更新下賬單小數，再計算總金額才不會錯
            updateOrderRounding();
            //更新合計 總金額信息
            mOrderContentActivity.initOrderDetail();
        }
    }

    /**
     * 更新整單折扣
     */
    protected void updateOrderDiscount() {
        BillOrderMoney orderMoney = getBillOrderItemByType(BillOrderMoney.ORDER_DISCOUNT_TYPE);
        if (orderMoney != null) {
            double totalMoney = getDiscountableFoodTotal(BillOrderMoney.ORDER_DISCOUNT_TYPE, false);
            double discountPrice = Discount.calculationDiscount(orderMoney.getDiscount(), totalMoney);
            orderMoney.setMoney(discountPrice);
        }
    }

    /**
     * 添加会员折扣
     *
     * @param memberId
     * @param discountRate
     * @param memberName
     * @param levelName
     */
    public void addMemberDiscount(long memberId, int discountRate, String memberName, String levelName, int status) {

        removeBillOrderItemByType(BillOrderMoney.MEMBER_DISCOUNT_TYPE);

        double totalMoney = getDiscountableFoodTotal(BillOrderMoney.MEMBER_DISCOUNT_TYPE, true);
        if (!TextUtils.isEmpty(levelName)) {
            memberName = memberName + "(" + levelName + ")";
        }
        double discountPrice = Discount.calculationMemberDiscount(discountRate, totalMoney);
        BillOrderMoney orderMoney = new BillOrderMoney();
        orderMoney.setMoney(discountPrice);
        orderMoney.setTitle(memberName + discountRate + "%");
        orderMoney.setType(BillOrderMoney.MEMBER_DISCOUNT_TYPE);
        orderMoney.setTextColor(ArmsUtils.getColor(IActivity, R.color.theme_black));
        orderMoney.setStatus(status);
        //折扣
        Discount discount = new Discount();
        discount.setId(memberId);
        discount.setMemberId(memberId);
        discount.setType(1);
        discount.setRemark(memberName + discountRate + "%");
        discount.setDiscount_value(discountRate);
        orderMoney.setDiscount(discount);

        mOrderMoneyList.add(orderMoney);
        mOrderMoneyAdapter.notifyDataSetChanged();
    }

    /**
     * 更新会员折扣
     */
    protected void updateMemberDiscount() {
        BillOrderMoney orderMoney = getBillOrderItemByType(BillOrderMoney.MEMBER_DISCOUNT_TYPE);
        if (orderMoney != null) {
            double totalMoney = getDiscountableFoodTotal(BillOrderMoney.MEMBER_DISCOUNT_TYPE, false);
            double discountPrice = Discount.calculationDiscount(orderMoney.getDiscount(), totalMoney);
            orderMoney.setMoney(discountPrice);
        }
    }

    /**
     * 添加优惠券折扣
     *
     * @param coupon
     * @param status
     */
    public void addCouponDiscount(CouponDiscountBean coupon, long memberId, int status) {

        removeBillOrderItemByType(BillOrderMoney.COUPON_DISCOUNT_TYPE);

        double totalMoney = getDiscountableFoodTotal(BillOrderMoney.COUPON_DISCOUNT_TYPE, true);
        double discountPrice = CouponDiscountBean.calculationCoupon(coupon.getDiscount(), coupon.getAmount(), totalMoney);
        BillOrderMoney orderMoney = new BillOrderMoney();
        orderMoney.setMoney(discountPrice);
        if (coupon.getDiscount() != 0) {
            orderMoney.setTitle(coupon.getName() + coupon.getDiscount() + "%");
        } else {
            orderMoney.setTitle(coupon.getName());
        }
        orderMoney.setType(BillOrderMoney.COUPON_DISCOUNT_TYPE);
        if (status == 0) {
            orderMoney.setTextColor(ArmsUtils.getColor(IActivity, R.color.theme_hint_color));
        } else {
            orderMoney.setTextColor(ArmsUtils.getColor(IActivity, R.color.theme_black));
        }
        orderMoney.setStatus(status);
        //折扣
        Discount discount = new Discount();
        discount.setId(coupon.getId());
        discount.setMemberId(memberId);
        discount.setRemark(coupon.getName() + coupon.getDiscount() + "%");
        discount.setDiscount_value(coupon.getDiscount());
        discount.setAmount(coupon.getAmount());
        if (coupon.getDiscount() != 0) {
            discount.setType(1);
        } else {
            discount.setType(0);
        }
        orderMoney.setDiscount(discount);

        mOrderMoneyList.add(orderMoney);
        mOrderMoneyAdapter.notifyDataSetChanged();
    }

    /**
     * 更新會員優惠券金額
     */
    public void updateMemberCoupon() {
        BillOrderMoney orderMoney = getBillOrderItemByType(BillOrderMoney.COUPON_DISCOUNT_TYPE);
        if (orderMoney != null) {
            double totalMoney = getDiscountableFoodTotal(BillOrderMoney.COUPON_DISCOUNT_TYPE, false);
            double discountPrice = CouponDiscountBean.calculationCoupon(orderMoney.getDiscount().getDiscount_value(), orderMoney.getDiscount().getAmount(), totalMoney);
            orderMoney.setMoney(discountPrice);
        }
    }

    /**
     * 根據類型刪除賬單項
     *
     * @param type
     */
    private void removeBillOrderItemByType(int type) {
        for (int i = mOrderMoneyList.size() - 1; i >= 0; i--) {
            BillOrderMoney item = mOrderMoneyList.get(i);
            if (item.getType() == type) {
                mOrderMoneyList.remove(i);
                mOrderMoneyAdapter.notifyItemChanged(i);
                break;
            }
        }
    }

    private BillOrderMoney getBillOrderItemByType(int type) {
        for (BillOrderMoney orderMoney : mOrderMoneyList) {
            if (orderMoney.getType() == type) {
                return orderMoney;
            }
        }
        return null;
    }

    /**
     * 更新食品折扣
     */
    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 = Discount.calculationDiscount(orderDetailsBean.getDiscount(), totalMoney);
                        //更新折扣金額
                        orderDetailsBean.setPrice(-discountPrice);
                        break;
                    } else {
                        if (orderDetailsBean.getAblediscount() == 0) {
                            //此食品或细项不支持折扣 直接跳过
                            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();
        }
    }

    /**
     * 添加賬單小數行
     */
    protected void addOrderRounding() {
        double m1 = getTotalAmountFilterByType(BillOrderMoney.ROUNDING_TYPE);
        double m2 = MoneyUtil.getOrderRounding(m1);
        double roundingMoney = 0.0;
        if (m2 != 0) {
            roundingMoney = MoneyUtil.sub(m2, MoneyUtil.get_ItemDecimals_money(m1));
        }
        if (roundingMoney != 0.0) {
            BillOrderMoney roundingItem = new BillOrderMoney();
            roundingItem.setMoney(MoneyUtil.getDecimalMoney(roundingMoney, MoneyUtil.ItemDecimals));
            roundingItem.setTitle("賬單小數");
            roundingItem.setType(BillOrderMoney.ROUNDING_TYPE);
            mOrderMoneyList.add(roundingItem);
            mOrderMoneyAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 刪除賬單小數
     */
    private void removeOrderRouding() {
        for (BillOrderMoney item : mOrderMoneyList) {
            if (item.getType() == BillOrderMoney.ROUNDING_TYPE) {
                mOrderMoneyList.remove(item);
                mOrderMoneyAdapter.notifyDataSetChanged();
                break;
            }
        }
    }

    /**
     * 更新賬單小數（在最後一行）
     */
    protected void updateOrderRounding() {
        removeOrderRouding();
        addOrderRounding();
    }

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

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

    /***
     * 獲取服務費
     * @return
     */
    public double getServiceCharge() {
        double serviceCharge = 0.0;
        for (BillOrderMoney item : mOrderMoneyList) {
            if (item.getType() == BillOrderMoney.SERVERCHARGE_TYPE) {
                serviceCharge = item.getMoney();
                break;
            }
        }
        return serviceCharge;
    }


    /**
     * 獲取食品合計
     *
     * @return
     */
    public double getFoodTotal() {
        double total = 0.0;
        for (OrderDetail food : myOrderManage.getOrderFoodList()) {
            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
     */
    public double getDiscountableFoodTotal(int discountType, boolean add) {
        double total = 0.0;
        List<OrderDetail> orderFoodList = myOrderManage.getOrderFoodList();
        int orderSize = orderFoodList.size();
        for (int i = 0; i < orderSize; i++) {
            OrderDetail food = orderFoodList.get(i);
            if (food.getNumber() == 0) {
                continue;
            }
            if (food.getItemType() == 1) {
                if (food.getAblediscount() == 1) {
                    total = MoneyUtil.sum(total, food.getPrice());
                }
            } else {
                int parentIndex = food.getParentIndex() - 1;
                if (orderSize > parentIndex && orderFoodList.get(parentIndex).getAblediscount() == 1) {
                    if (food.getType() == DISCOUNT_TYPE) {
                        //主食品参与折扣,折扣金额直接减掉
                        total = MoneyUtil.sub(total, Math.abs(food.getPrice()));
                    } else {
                        //主食品可參與折扣 子食品才能參與折扣
                        if (food.getAblediscount() == 1) {
                            total = MoneyUtil.sum(total, food.getPrice());
                        }
                    }
                }
            }
        }
        if (add) {
            //添加折扣
            //折上折的情况,先减去上面的折扣金额再进行折扣
            for (int i = 0; i < mOrderMoneyList.size(); i++) {
                BillOrderMoney billOrderMoney = mOrderMoneyList.get(i);
                if (billOrderMoney.getType() == BillOrderMoney.ORDER_DISCOUNT_TYPE || billOrderMoney.getType() == BillOrderMoney.MEMBER_DISCOUNT_TYPE || billOrderMoney.getType() == BillOrderMoney.COUPON_DISCOUNT_TYPE) {
                    double money = billOrderMoney.getMoney();
                    total = MoneyUtil.sum(total, money);
                    break;
                }
            }
        } else {
            //更新折扣
            int containAllDiscount = 0;
            for (int i = 0; i < mOrderMoneyList.size(); i++) {
                BillOrderMoney billOrderMoney = mOrderMoneyList.get(i);
                if (billOrderMoney.getType() == BillOrderMoney.ORDER_DISCOUNT_TYPE) {
                    containAllDiscount++;
                    continue;
                }
                if (billOrderMoney.getType() == BillOrderMoney.MEMBER_DISCOUNT_TYPE) {
                    containAllDiscount++;
                    continue;
                }
                if (billOrderMoney.getType() == BillOrderMoney.COUPON_DISCOUNT_TYPE) {
                    containAllDiscount++;
                    continue;
                }
            }
            if (containAllDiscount > 1) {
                //有账单折扣+会员折扣 会员优惠券
                //折上折的情况,先减去上之前的折扣金额再进行折扣
                for (int i = 0; i < mOrderMoneyList.size(); i++) {
                    BillOrderMoney billOrderMoney = mOrderMoneyList.get(i);
                    if (billOrderMoney.getType() == discountType) {
                        //不能减掉自身再折
                        break;
                    }
                    if (billOrderMoney.getType() == BillOrderMoney.ORDER_DISCOUNT_TYPE || billOrderMoney.getType() == BillOrderMoney.MEMBER_DISCOUNT_TYPE || billOrderMoney.getType() == BillOrderMoney.COUPON_DISCOUNT_TYPE) {
                        double money = billOrderMoney.getMoney();
                        total = MoneyUtil.sum(total, money);
                        break;
                    }
                }
            }
        }
        if (total < 0) {
            total = 0;
        }
        return MoneyUtil.get_ItemDecimals_money(total);
    }

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

    /**
     * 獲取總金額
     *
     * @return
     */
    public double getTotalAmountFilterByType(int... filterTypes) {
        double foodTotal = getFoodTotal();
        for (BillOrderMoney item : mOrderMoneyList) {
            if (!filterType(item.getType(), filterTypes)) {
                if (item.getType() == BillOrderMoney.SERVERCHARGE_TYPE && mOrderMoneyAdapter.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 (BillOrderMoney item : mOrderMoneyList) {
            if (item.getType() == BillOrderMoney.SERVERCHARGE_TYPE && mOrderMoneyAdapter.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 (BillOrderMoney item : mOrderMoneyList) {
            if (item.getType() == BillOrderMoney.ROUNDING_TYPE) {
                return item.getMoney();
            }
        }
        return null;
    }

    /**
     * 獲取食品總數量
     *
     * @return
     */
    public int getFoodCount() {
        int count = 0;
        for (OrderDetail food : myOrderManage.getOrderFoodList()) {
            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();
//        int start_position = mSelectMealAdapter.getSelect_full_start_position();
//        int end_position = mSelectMealAdapter.getSelect_full_end_position();
        for (int i = orderDetails.size() - 1; i >= 0; i--) {
//            if (start_position <= i && i <= end_position) {
            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> getSelectedOldFoodAndDicount() {
        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 (GsaCloudApplication.androidSetting.isMergeSendFood()) {
            //合并未送单主食品
            mergeMainFoodNumber(newFoodList);
        }

        setChildScAbleByMainAble(newFoodList);
        setChildDiscountByMainAblediscount(newFoodList);

        int restaurantId = GsaCloudApplication.getRestaurantId();
        CreateOrderRequest request = new CreateOrderRequest();
        request.setTableNumber(OpenTableManage.getDefault().getTableBean().getTableNumber());
        request.setOrderDetails(orderDetailBeanToFoodRequest(newFoodList));
        request.setPerson(OpenTableManage.getDefault().getPeopleNumber());
        request.setTableId(OpenTableManage.getDefault().getTableBean().getId());
        request.setTableName(OpenTableManage.getDefault().getTableBean().getTableName());
        request.setRounding(getRounding());
        request.setRestaurantId(restaurantId);

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


    protected AddOrderRequest getAddOrderRequest(List<OrderDetail> foodList) {
        List<OrderDetail> newFoodList = OrderDetail.transNewOrderDetails(foodList);
        if (GsaCloudApplication.androidSetting.isMergeSendFood()) {
            //合并未送单主食品
            mergeMainFoodNumber(newFoodList);
        }

        setChildScAbleByMainAble(newFoodList);
        setChildDiscountByMainAblediscount(newFoodList);

        AddOrderRequest request = new AddOrderRequest();
        request.setOrderId(MyOrderManage.getInstance().getOrderId());
        request.setTableId(OpenTableManage.getDefault().getTableBean().getId());
        if (MyOrderManage.getInstance().getMemberInfo() != null) {
            request.setMemberId(MyOrderManage.getInstance().getMemberInfo().getId());
        }
        request.setTableNumber(OpenTableManage.getDefault().getTableBean().getTableNumber());
        request.setMaps(orderDetailBeanToAddFoodRequest(newFoodList));
        if (myOrderManage.getDeleteOrders() != null) {
            request.setDeleteOrders(myOrderManage.getDeleteOrders());
        }

        Double rounding = getRounding();
        request.setRounding(rounding != null ? rounding : 0);

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

    private List<OrderDiscount.Request> getOrderDiscountDetails() {

        List<OrderDiscount.Request> discountRequests = new ArrayList<>();

        for (BillOrderMoney item : mOrderMoneyList) {
            if (item.getType() == BillOrderMoney.ORDER_DISCOUNT_TYPE) {
                discountRequests.add(OrderDiscount.Request.orderDiscountTransRequest(item));
                continue;
            }
            if (item.getType() == BillOrderMoney.MEMBER_DISCOUNT_TYPE) {
                discountRequests.add(OrderDiscount.Request.memberDiscountTransRequest(item));
                continue;
            }
            if (item.getType() == BillOrderMoney.COUPON_DISCOUNT_TYPE) {
                discountRequests.add(OrderDiscount.Request.couponDiscountTransRequest(item));
                continue;
            }
        }
        return discountRequests;
    }

    protected Map<Long, List<OrderBean.OrderDetailsBean>> orderDetailBeanToFoodRequest(List<OrderDetail> foodList) {
        Map<Long, List<OrderBean.OrderDetailsBean>> orderDetails = new HashMap<>();
        if (foodList != null) {
            //套餐明細ID
            long mapIndex = 0;
            //主食品ID
            long mainProductId = 0;
            //打印用到，清理掉之前保存的食品
            MyOrderManage.getInstance().getNewFoodList().clear();
            List<OrderBean.OrderDetailsBean> orderItems = null;
            for (int i = 0; i < foodList.size(); i++) {
                OrderDetail item = foodList.get(i);
                if (item.getType() == DISCOUNT_TYPE) {
                    //折扣直接跳過
                    continue;
                }
                if (item.getItemType() == 1) {
                    orderItems = new ArrayList<>();
                    mapIndex += 1;
                    //主食品ID
                    mainProductId = item.getProductId();
                }

                OrderBean.OrderDetailsBean request = new OrderBean.OrderDetailsBean();
                request.setMemberId(GsaCloudApplication.getMemberId());
                request.setProductName(item.getProductName());
                request.setProductId(item.getProductId());
                request.setParentId(item.getParentId());
                request.setTopId(item.getTopId());
                request.setNumber(item.getNumber());
                request.setPrice(item.getUnit_price());
                request.setType(item.getType());
                request.setPrintSetIng(item.getPrintseting());
                request.setAblediscount(item.getAblediscount());
                request.setScAble(item.getScAble());
                request.setDiscountId(getDiscountIdByParentId(foodList, mainProductId));
                request.setLunchboxPrice(0);
                request.setPointsAdd(item.getPointsAdd());
                request.setPointsRedeem(item.getPointsRedeem());
                if (item.isNew()) {
                    //這裡只添加新食品
                    orderItems.add(request);
                    //保存新食品，打印用到
                    MyOrderManage.getInstance().getNewFoodList().add(item);
                }
                int nextIndex = i + 1;
                if (foodList.size() > nextIndex && foodList.get(nextIndex).getType() == DISCOUNT_TYPE) {
                    //下一個是折扣，跳過往下找
                    nextIndex++;
                }
                if (foodList.size() > nextIndex) {
                    if (orderItems != null && orderItems.size() > 0 && foodList.get(nextIndex).getItemType() == 1) {
                        //下一個食品是不是主食品
                        orderDetails.put(mapIndex, orderItems);
                    }
                } else if (foodList.size() == nextIndex) {
                    //最後
                    if (orderItems != null && orderItems.size() > 0) {
                        orderDetails.put(mapIndex, orderItems);
                    }
                }
            }
        }
        return orderDetails;
    }

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

                OrderBean.OrderDetailsBean request = new OrderBean.OrderDetailsBean();
                request.setMemberId(GsaCloudApplication.getMemberId());
                request.setOrderId(MyOrderManage.getInstance().getOrderId());
                if (item.getId() != 0) {
                    request.setId(item.getId());
                }
                request.setProductName(item.getProductName());
                request.setProductId(item.getProductId());
                request.setParentId(item.getParentId());
                request.setTopId(item.getTopId());
                request.setNumber(item.getNumber());
                request.setPrice(item.getUnit_price());
                request.setType(item.getType());
                request.setPrintSetIng(item.getPrintseting());
                request.setAblediscount(item.getAblediscount());
                request.setScAble(item.getScAble());
                request.setDiscountId(getDiscountIdByParentId(foodList, mainParentId));
                request.setLunchboxPrice(0);
                request.setPointsAdd(item.getPointsAdd());
                request.setPointsRedeem(item.getPointsRedeem());
                if (item.isNew() || item.getDiscountStatus() == 1) {
                    //這裡只添加新食品或有新折扣食品
                    orderItems.add(request);
                    //保存新食品，打印用到
                    MyOrderManage.getInstance().getNewFoodList().add(item);
                }
                int nextIndex = i + 1;
                if (foodList.size() > nextIndex && foodList.get(nextIndex).getType() == DISCOUNT_TYPE) {
                    //下一個是折扣，跳過往下找
                    nextIndex++;
                }
                if (foodList.size() > nextIndex) {
                    if (orderItems != null && orderItems.size() > 0 && foodList.get(nextIndex).getItemType() == 1) {
                        //下一個食品是不是主食品
                        orderDetails.put(mapIndex, orderItems);
                    }
                } else if (foodList.size() == nextIndex) {
                    //最後
                    if (orderItems != null && orderItems.size() > 0) {
                        orderDetails.put(mapIndex, orderItems);
                    }
                }
            }
        }
        return orderDetails;
    }


    /**
     * 送单前根据主食品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).getAblediscount() == 0) {
                    //主食品不可參與折扣 子食品也不能參與折扣
                    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).getAblediscount() == 0) {
                    //主食品不可參與折扣 子食品也不能參與折扣
                    food.setScAble((byte) 0);
                }
            }
        }
    }

    /**
     * 合并新下单主食品数量
     *
     * @param foodList
     */
    private 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 discountList
     * @return
     */
    protected List<Discount> filterDiscountByType(List<Discount> discountList, String discountType) {
        for (int i = discountList.size() - 1; i >= 0; i--) {
            Discount discount = discountList.get(i);
            if (TextUtils.isEmpty(discount.getDiscountType()) || !discount.getDiscountType().contains(discountType)) {
                discountList.remove(i);
            }
        }
        return discountList;
    }

    /**
     * 是否包含子项
     *
     * @param orderDetailList
     * @param orderDetail
     * @return
     */
    private boolean hasChildFood(List<OrderDetail> orderDetailList, OrderDetail orderDetail) {
        if (orderDetail.getItemType() == 3) {
            return false;
        }
        for (int i = 0; i < orderDetailList.size(); i++) {
            if (orderDetailList.get(i).getParentIndex() == orderDetail.getMyIndex()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 根據主食品ID獲取對應折扣ID
     *
     * @param orderItems
     * @param mainParentId
     * @return
     */
    private Long getDiscountIdByParentId(List<OrderDetail> orderItems, long mainParentId) {
        Long discountId = null;
        for (OrderDetail item : orderItems) {
            if (item.getType() == DISCOUNT_TYPE && item.getParentId() == mainParentId) {
                discountId = item.getProductId();
                break;
            }
        }
        return discountId;
    }

    /**
     * 獲取優惠券折扣ID
     *
     * @return
     */
    protected Long getCouponDiscountId() {
        for (BillOrderMoney item : mOrderMoneyList) {
            if (item.getType() == BillOrderMoney.COUPON_DISCOUNT_TYPE && item.getDiscount() != null) {
                return item.getDiscount().getId();
            }
        }
        return null;
    }

    /**
     * 返回未送單整單折扣
     *
     * @return
     */
    protected BillOrderMoney getNewDiscount() {
        for (BillOrderMoney item : mOrderMoneyList) {
            if (item.getStatus() == 0 &&
                    (item.getType() == BillOrderMoney.ORDER_DISCOUNT_TYPE ||
                            item.getType() == BillOrderMoney.MEMBER_DISCOUNT_TYPE||
                            item.getType() == BillOrderMoney.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;
    }


    protected 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 myOrderManage.getOrderFoodList();
    }


    protected String getTableName() {
        String tablename = "";
        if (OpenTableManage.getDefault().isSplite()) {
            tablename = OpenTableManage.getDefault().getTableBean().getTableName() + "-" + OpenTableManage.getDefault().getSplitNo();
        } else {
            tablename = OpenTableManage.getDefault().getTableBean().getTableName();
        }
        return tablename;
    }

    /**
     * 修改訂單
     *
     * @param //orderId 訂單號
     * @param //person  人數
     */
    public void updateOrderPerson(String peopleNumber, TextView textView) {
        RequestBody requestBody = new FormBody.Builder()
                .add("orderId", String.valueOf(MyOrderManage.getInstance().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);
                            }
                            OpenTableManage.getDefault().setPeopleNumber(Integer.parseInt(peopleNumber));
                        }
                    }
                });
    }
}

