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

import android.app.Activity;
import android.app.Application;
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.BillOrderMoney;
import com.gingersoft.gsa.cloud.base.common.bean.OrderBean;
import com.gingersoft.gsa.cloud.base.common.bean.OrderDetail;
import com.gingersoft.gsa.cloud.base.common.bean.TableBean;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.OpenTableManage;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.database.bean.Discount;
import com.gingersoft.gsa.cloud.table.R;
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.ui.activity.OrderContentActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.OrderMoneyAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.SelectMealAdapter;
import com.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
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.common.bean.OrderDetail.DISCOUNT_PROP;
import static com.gingersoft.gsa.cloud.base.common.bean.OrderDetail.DISCOUNT_TYPE;

/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2020-01-11
 * 修订历史：2020-01-11
 * 描述：
 */

@ActivityScope
public class BaseOrderPresenter<M extends BaseOrderContract.Model, V extends BaseOrderContract.View> extends BasePresenter<BaseOrderContract.Model, BaseOrderContract.View> {

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

    protected M mModel;
    protected V mRootView;

    private Activity IActivity;
    private OrderContentActivity mOrderContentActivity;
    private MealStandPresenter mMealStandPresenter;
    private OrderContentPresenter mOrderContentPresenter;
    private OrderPayPresenter mOrderPayPresenter;

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

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

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

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

    //币種
    public String cashStr = "$";

    private final String noFoodDeliveryTip = "賬單沒有食品，是否開台?";

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

    @Inject
    public BaseOrderPresenter(BaseOrderContract.Model model, BaseOrderContract.View rootView) {
        super(model, rootView);
        this.mModel = (M) model;
        this.mRootView = (V) rootView;
        this.IActivity = (Activity) mRootView;
        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;
        } else if (this instanceof OrderContentPresenter) {
            mOrderContentPresenter = (OrderContentPresenter) this;
        } else if (this instanceof OrderPayPresenter) {
            mOrderPayPresenter = (OrderPayPresenter) this;
        }

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

        addSentOrderMoney();
        addOrderRounding();

        //設置賬單總金額
        myOrderManage.setTotalAmount(getTotalAmount());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = 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();
                }
                //更新折扣
                updateOrderMoneyItem();
            }

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

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

    public void changeNumber(int number) {
        if (!changeNumberCondition(number)) {
            return;
        }
        myOrderManage.changeNumber(number);
        if (mMealStandPresenter != null) {
            mMealStandPresenter.updateOrderFoodNumber();
        }
        updateOrderMoneyItem();
        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;
        }
        return true;
    }

    /**
     * 送單
     *
     * @param isPrint 是否印單
     */
    public void sendOrder(boolean isPrint) {
        if (MyOrderManage.getInstance().getOrderId() == -1) {
            if (getFoodSize() == 0) {
                Class[] parameterTypes = {boolean.class};
                Object[] parameters = {isPrint};
                CommonTipDialog.showDoubtDialog(IActivity, noFoodDeliveryTip, BaseOrderPresenter.class, this,
                        "executeCreateOrder", parameterTypes, parameters);
            } else {
                executeCreateOrder(isPrint);
            }
        } else {
            executeAddOrderFood(isPrint);
        }
    }

    private void executeCreateOrder(boolean isPrint) {
        if (mMealStandPresenter != null) {
            mMealStandPresenter.createOrder();
        } else if (mOrderContentPresenter != null) {
            mOrderContentPresenter.createOrder(isPrint);
        } else if (mOrderPayPresenter != null) {
            mOrderPayPresenter.createOrder();
        }
    }

    private void executeAddOrderFood(boolean isPrint) {
        if (mMealStandPresenter != null) {
            mMealStandPresenter.addOrderFood();
        } else if (mOrderContentPresenter != null) {
            mOrderContentPresenter.addOrderFood(isPrint);
        } else if (mOrderPayPresenter != null) {
            mOrderPayPresenter.addOrderFood();
        }
    }

    /**
     * 添加已送單折扣，服務費
     */
    private void addSentOrderMoney() {
        OrderBean orderBean = myOrderManage.getOrderBean();
        if (orderBean != null) {
            //折扣
            Discount discount = new Discount();
            discount.setType(orderBean.getType());
            discount.setRemark(orderBean.getRemark());
            if (orderBean.getDiscountValue() != 0) {
                //百分比折扣
                discount.setDiscount_value(orderBean.getDiscountValue());
                addOrderDiscount(discount, 1, true);
            }
            if (orderBean.getDiscountAmount() != 0) {
                //金額折扣
                discount.setAmount(orderBean.getDiscountAmount());
                addOrderDiscount(discount, 1, true);
            }
        }
    }

    /**
     * 更新賬單金額
     */
    protected void updateOrderMoneyItem(){
        updateOrderDiscount();
        updateOrderRounding();
    }

    /**
     * 添加賬單折扣
     *
     * @param discount
     */
    protected void addOrderDiscount(Discount discount, int status, boolean sentOrder) {
        double totalMoney = getFoodTotal();
        double discountPrice = Discount.calculationDiscount(discount, totalMoney);
        BillOrderMoney orderMoney = new BillOrderMoney();
        orderMoney.setMoney(discountPrice);
        orderMoney.setTitle(discount.getRemark());
        orderMoney.setType(BillOrderMoney.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);
        if (sentOrder) {
            mOrderMoneyList.clear();
        }
        mOrderMoneyList.add(orderMoney);
        mOrderMoneyAdapter.notifyDataSetChanged();
        //更新總金額
        if (!sentOrder && mOrderContentActivity != null) {
            mOrderContentActivity.initOrderDetail();
        }
    }

    /**
     * 更新折扣金額
     */
    protected void updateOrderDiscount() {

        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 {
                        //保存每個食品套餐折扣總額
                        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 = getTotalAmount();
        double m2 = MoneyUtil.getOrderRounding(m1);
        double roundingMoney = 0.0;
        if (m2 != 0) {
            roundingMoney = m2 - MoneyUtil.get_ItemDecimals_money(m1);
        }
        if (roundingMoney != 0.00) {
            BillOrderMoney roundingItem = new BillOrderMoney();
            roundingItem.setMoney(MoneyUtil.getDecimalMoney(roundingMoney,MoneyUtil.ItemDecimals));
            roundingItem.setTitle("賬單小數");
            roundingItem.setType(BillOrderMoney.ROUNDING_TYPE);
            mOrderMoneyList.add(roundingItem);
            mOrderMoneyAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 更新賬單小數（在最後一行）
     */
    protected void updateOrderRounding(){
        for (BillOrderMoney item: mOrderMoneyList) {
            if(item.getType() == BillOrderMoney.ROUNDING_TYPE){
                mOrderMoneyList.remove(item);
                mOrderMoneyAdapter.notifyDataSetChanged();
                addOrderRounding();
                break;
            }
        }
    }

    /**
     * 創建訂單后保存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 getFoodTotal() {
        double total = 0.0;
        for (OrderDetail food : myOrderManage.getOrderFoodList()) {
            total = MoneyUtil.sum(total, food.getPrice());
        }
        return MoneyUtil.get_ItemDecimals_money(total);
    }

    /**
     * 獲取總金額:已減去折扣,服務費
     *
     * @return
     */
    public double getTotalAmount() {
        double foodTotal = getFoodTotal();
        for (BillOrderMoney item : mOrderMoneyList) {
            foodTotal = MoneyUtil.sum(foodTotal, item.getMoney());
            if (0 > foodTotal) {
                //折扣金額不能超出總額
                foodTotal = 0;
            }
        }
        return MoneyUtil.get_ItemDecimals_money(foodTotal);
    }

    /**
     * 獲取賬單小數
     * @return
     */
    private  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()) {
            count += food.getNumber();
        }
        return count;
    }

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

    /**
     * 返回選中已送單食品ID
     *
     * @return
     */
    protected String getSelectOldFoodIds() {
        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.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 int getSelectComboNumber() {
        int comboNumber = 0;
        List<OrderDetail> orderDetails = getOrderFoodLists();
        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.getProp() == OrderDetail.COMBO_PROP) {
                    comboNumber++;
                }
            }
        }
        return comboNumber;
    }

    protected CreateOrderRequest getCreateOrderRequest(List<OrderDetail> foodList) {
        int restaurantId = GsaCloudApplication.getRestaurantId(mApplication);
        CreateOrderRequest request = new CreateOrderRequest();
        request.setOrderDetails(orderDetailBeanToFoodRequest(foodList));
        request.setPerson(OpenTableManage.getDefault().getPeopleNumber());
        request.setTableId(OpenTableManage.getDefault().getTableBean().getId());
        request.setTableName(OpenTableManage.getDefault().getTableBean().getTableName());
        request.setRounding(getRounding());
        request.setRestaurantId(restaurantId);
        Discount orderDiscount = getNesOrderDiscount();
        if (orderDiscount != null) {
            request.setDiscountId(orderDiscount.getId());
        }
        return request;
    }

    protected AddOrderRequest getAddOrderRequest(List<OrderDetail> foodList) {
        AddOrderRequest request = new AddOrderRequest();
        request.setMaps(orderDetailBeanToAddFoodRequest(foodList));
        request.setOrderId(MyOrderManage.getInstance().getOrderId());
        request.setRounding(getRounding());
        Discount orderDiscount = getNesOrderDiscount();
        if (orderDiscount != null) {
            request.setDiscountId(orderDiscount.getId());
        }
        return request;
    }

    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() == OrderDetail.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(mApplication));
                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.setDiscountId(getDiscountIdByParentId(foodList, mainProductId));
                request.setLunchboxPrice(0);
                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() == OrderDetail.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(mApplication));
                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.setDiscountId(getDiscountIdByParentId(foodList, mainParentId));
                request.setLunchboxPrice(0);
                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;
    }

    /**
     * 根據主食品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;
    }

    /**
     * 返回未送單整單折扣
     *
     * @return
     */
    protected Discount getNesOrderDiscount() {
        for (BillOrderMoney item : mOrderMoneyList) {
            if (item.getStatus() == 0 && item.getType() == BillOrderMoney.DISCOUNT_TYPE) {
                return item.getDiscount();
            }
        }
        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 void sortSelectMealByIsNew() {
        List<OrderDetail> orderDetail = mOrderFoodList;
        List<OrderDetail> sortOrderList = new ArrayList<>();
        for (int i = 0; i < orderDetail.size(); i++) {
            sortOrderList.add(orderDetail.get(i));
        }
        Comparator c = new Comparator<OrderDetail>() {
            @Override
            public int compare(OrderDetail o1, OrderDetail o2) {
                Boolean isnew1 = o1.isNew();
                Boolean isnew2 = o2.isNew();
                return isnew1.compareTo(isnew2);
            }
        };
        Collections.sort(sortOrderList, c);
        orderDetail.clear();
        for (int i = 0; i < sortOrderList.size(); i++) {
            orderDetail.add(sortOrderList.get(i));
        }
    }

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

//    protected String replacer(String str) {
//        String data = str;
//        try {
//            data = data.replaceAll("%(?![0-9a-fA-F]{2})", "%25").replaceAll("\\+", "%2B");
////            data = URLDecoder.decode(data);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return data;
//    }

    /**
     * 修改訂單
     *
     * @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));
                        }
                    }
                });
    }
}

