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

import android.app.Application;
import android.text.TextUtils;
import android.util.SparseArray;
import com.gingersoft.gsa.cloud.common.constans.MealConstant;
import com.gingersoft.gsa.cloud.common.core.member.MemberInfo;
import com.gingersoft.gsa.cloud.common.logan.LoganManager;
import com.gingersoft.gsa.cloud.common.rxjava.ErrorHandleSingleSubscriber;
import com.gingersoft.gsa.cloud.common.rxjava.MyRxSchedulerUtils;
import com.gingersoft.gsa.cloud.common.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.database.bean.ComboItem;
import com.gingersoft.gsa.cloud.database.bean.Discount;
import com.gingersoft.gsa.cloud.database.bean.Food;
import com.gingersoft.gsa.cloud.database.bean.FoodCombo;
import com.gingersoft.gsa.cloud.database.bean.Modifier;
import com.gingersoft.gsa.cloud.database.utils.ModifierDaoUtils;
import com.gingersoft.gsa.cloud.order.commodity.OrderDetail;
import com.gingersoft.gsa.cloud.order.order.BaseOrder;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.SoldoutCtrFood;
import com.gingersoft.gsa.cloud.table.mvp.presenter.BaseOrderPresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.ComboAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.FoodAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.FoodGroupAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.ModifierAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.SelectMealAdapter;
import com.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
import com.jess.arms.base.delegate.IActivity;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;

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

import com.gingersoft.gsa.cloud.table.mvp.contract.SetMealContract;
import com.jess.arms.utils.RxLifecycleUtils;
import com.xuexiang.rxutil2.rxjava.RxSchedulerUtils;

import org.simple.eventbus.Subscriber;

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

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


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/17/2021 10:40
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@FragmentScope
public class SetMealPresenter extends BaseOrderPresenter<SetMealContract.Model, SetMealContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

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

    @Inject
    FoodGroupAdapter mFoodGroupAdapter;
    @Inject
    FoodAdapter mFoodAdapter;
    @Inject
    ComboAdapter mComboAdapter;
    @Inject
    ModifierAdapter mModifierAdapter;

    private OrderDetail mCurrentOrderDetailBean;
    //沽清食品數據
    private List<SoldoutCtrFood> mSoldoutCtrList;

    private boolean RvMealClicked;

    @Inject
    public SetMealPresenter(SetMealContract.Model model, SetMealContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void createOrder(boolean isPrint, Class<?> afterToActivity) {

    }

    @Override
    public void addOrderFood(boolean isPrint, Class<?> afterToActivity) {

    }

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

    public void modifierItemClick(Modifier datasBean) {
        RvMealClicked = false;

        if (!modifierConditionFilter(datasBean)) {
            return;
        }
        if (cutOutModifier(datasBean) == -100) {
            //已送單數量已等於最大數，不能繼續添加
            return;
        }

        addModifierItem(datasBean);
        //更新賬單數
//        updateOrderFoodNumber();
        //沽清細項沽清數
        updateModifierSoldoutCtrData();
    }

    public void comboItemClick(ComboItem datasBean) {
        RvMealClicked = false;

        if (!comboConditionFilter(datasBean)) {
            return;
        }
        if (cutOutCombo(datasBean) == -100) {
            //已送單數量已等於最大數，不能繼續添加
            return;
        }

        //设置当前操作的套餐细项
        long id = mCurrentOrderDetailBean.isNew() ? mCurrentOrderDetailBean.getProductId() : mCurrentOrderDetailBean.getId();
        mCurrentOrderDetailBean = OrderDetail.comboTransOrderDetail(datasBean, id, mCurrentOrderDetailBean.getProductId(), 1, OrderDetail.COMBO_PROP, RvMealClicked);
        //添加子项
        addComboItem(mCurrentOrderDetailBean);
        //沽清子食品沽清數
        updateComboItemSoldoutCtrData();
        //更新賬單金額
        updateBillInfo();
        //更新賬單數
//        updateOrderFoodNumber();
    }

    public void foodItemClick(Food datasBean) {
        if (mSelectMealAdapter.getSelectedMode() == SelectMealAdapter.MULTIPLE_SELECTED) {
            return;
        }
        if (!foodConditionFilter(datasBean)) {
            return;
        }

        RvMealClicked = false;
        if (datasBean.getIsParent() == 0) {
            queryFoodListByParentId(datasBean.getId());
        } else {
            mCurrentOrderDetailBean = OrderDetail.foodTransOrderDetails(datasBean, 1);
            int customType = datasBean.ableDiscountCastCustomType();
            if (customType != Food.CUSTOM_TYPE_100) {
                //自定義食品
//                mRootView.setCustomFoodDialog(customType, mCurrentOrderDetailBean);
            } else {
                //加載套餐食品
                loadComboData(mCurrentOrderDetailBean, false);
            }
        }
    }
    private void addFoodItemBefore(OrderDetail datasBean) {
        int addPosition = addFoodItem(datasBean);
        //这里主食品作为选中主体
        mRootView.setMealRvScrollToPosition(addPosition);
    }

    private int addFoodItem(OrderDetail orderDetail) {
        int addPosition = mSelectMealAdapter.addFoodItem(orderDetail);
        if (orderDetail.getComboLevel() > 0) {
            if (mComboList != null && mComboList.size() > 0) {
                for (int i = 0; i < mComboList.size(); i++) {
                    //自动添加组合子食品
                    ComboItem comboItem = mComboList.get(i);
//                    if (comboItem.isSold()) {
//                        String msg = "[" + comboItem.getName() + "]" + comboItem.getCurrentMaxNumber();
//                        CommonTipDialog.showSurpisedDialog(IActivity, msg, null, null, null, null, null);
//                        continue;
//                    }
                    if (comboItem.getInvisible() != 2) {
                        int defNumber = Integer.parseInt(comboItem.getDefmodifier());
                        if (defNumber != 0) {
                            long id = mCurrentOrderDetailBean.isNew() ? mCurrentOrderDetailBean.getProductId() : mCurrentOrderDetailBean.getId();
                            mCurrentOrderDetailBean = OrderDetail.comboTransOrderDetail(comboItem, id, mCurrentOrderDetailBean.getProductId(), defNumber, OrderDetail.COMBO_PROP, RvMealClicked);
                            addPosition = addComboItem(mCurrentOrderDetailBean);
                        }
                    }
                }
            }
        }
        //自动添加mixqty>1細項
        for (int i = 0; i < mModifierList.size(); i++) {
            Modifier modfier = mModifierList.get(i);
//            if (modfier.isSold()) {
//                String msg = "[" + modfier.getModifierName() + "]" + modfier.getCurrentMaxNumber();
//                CommonTipDialog.showSurpisedDialog(IActivity, msg, null, null, null, null, null);
//                continue;
//            }
            if (modfier.getInvisible() != 2) {
                int defNumber = Integer.parseInt(modfier.getDefmodifier());
                if (defNumber != 0) {
                    long id = mCurrentOrderDetailBean.isNew() ? mCurrentOrderDetailBean.getProductId() : mCurrentOrderDetailBean.getId();
                    addPosition = mSelectMealAdapter.addFoodItem(OrderDetail.modifierTransOrderDetail(modfier, id, mCurrentOrderDetailBean.getProductId(), defNumber));
                }
            }
        }
        return addPosition;
    }

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

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

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

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

//        IActivity.setFineItemSlodoutListFull(mSoldoutCtrList);

        mRootView.setMealRvScrollToPosition(addPosition);
    }

    private void addDiscountItem(Discount datasBean) {
        //主食品ID
        long id = 0;
        if (mSelectMealAdapter.getCurrentMainOrderDetail() != null) {
            if (mCurrentOrderDetailBean.isNew()) {
                id = mSelectMealAdapter.getCurrentMainOrderDetail().getProductId();
            } else {
                id = mSelectMealAdapter.getCurrentMainOrderDetail().getId();
            }
        }
//        mCurrentOrderDetailBean = OrderDetail.discountTransOrderDetail(datasBean, true, id, getDisountSourcePrice());
        int addPosition = mSelectMealAdapter.addFoodItem(mCurrentOrderDetailBean);
        mRootView.setMealRvScrollToPosition(addPosition);

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

    private void loadComboData(OrderDetail food, boolean isSelectedMeal) {
        Observable.create(new ObservableOnSubscribe<List>() {
            @Override
            public void subscribe(ObservableEmitter<List> emitter) throws Exception {
                long fid = food.getProductId();
                int itemType = food.getItemType();

                List<ComboItem> comboItemList = new ArrayList<>();
                if (itemType == 1) {
                    //获取套餐细项数据
//                    List<ComboItem> comboItems = mModel.queryDB_ComboList(fid, BaseOrder.orderType);
//                    comboItemList.addAll(comboItems);
                }
//                List<Modifier> modifierList = mModel.queryDB_ModifierList(fid, ModifierDaoUtils.modifierMode_All);
//
//                emitter.onNext(comboItemList);
//                emitter.onNext(modifierList);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io())//在IO线程执行数据库处理操作
                .observeOn(AndroidSchedulers.mainThread())//在UI线程
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new Observer<List>() {

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

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

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

                    @Override
                    public void onError(Throwable e) {
                    }

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

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

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

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

    private int getCutPositionByOutLimitModifier(Modifier modifier) {
        int mainOrderNumber = 1;
        int oldCount = 0;
        SparseArray<String> numberAndCutPositionMap = new SparseArray<>();
        OrderDetail currentMainOrderDetail = mSelectMealAdapter.getCurrentMainOrderDetail();
        if (currentMainOrderDetail != null) {
            int start_position = mSelectMealAdapter.getSelect_full_start_position();
            int end_position = mSelectMealAdapter.getSelect_full_end_position();
            for (int i = mOrderMealList.size() - 1; i >= 0; i--) {
                if (start_position <= i && i <= end_position) {
                    OrderDetail item = mOrderMealList.get(i);
                    if (item.getItemType() == 1) {
                        mainOrderNumber = item.getNumber();
                    }
                    if (item.getItemType() == 3 && item.getTopId() == modifier.getTopId()) {
                        //同一食品下的細項
                        String comboIdAndNumber = numberAndCutPositionMap.get((int) item.getTopId());
                        int cutPosition = i;
                        String value;
                        if (comboIdAndNumber != null) {
                            String[] splitStr = numberAndCutPositionMap.get((int) item.getTopId()).split("_");
                            if (item.isNew()) {
                                value = (Integer.parseInt(splitStr[0]) + item.getNumber()) + "_" + cutPosition;
                            } else {
                                //已下單不可替換刪除
                                if (splitStr.length > 1) {
                                    value = (Integer.parseInt(splitStr[0]) + item.getNumber()) + "_" + splitStr[1];
                                } else {
                                    value = (Integer.parseInt(splitStr[0]) + item.getNumber()) + "_";
                                }
                                oldCount++;
                            }
                        } else {
                            if (item.isNew()) {
                                value = item.getNumber() + "_" + cutPosition;
                            } else {
                                //已下單不可替換刪除
                                value = item.getNumber() + "_";
                                oldCount++;
                            }
                        }
                        numberAndCutPositionMap.put((int) item.getTopId(), value);
                    }
                }
            }
        }
        for (int i = 0; i < numberAndCutPositionMap.size(); i++) {
            String[] numberAndCutPositionStr = numberAndCutPositionMap.valueAt(i).split("_");
            int number = Integer.parseInt(numberAndCutPositionStr[0]);
            int maxQty = modifier.getSelectQty() * mainOrderNumber;
            if (numberAndCutPositionStr.length > 1 && !TextUtils.isEmpty(numberAndCutPositionStr[1])) {
                int cutPosition = Integer.parseInt(numberAndCutPositionStr[1]);
                if (maxQty <= number && cutPosition < mOrderMealList.size()) {
                    return cutPosition;
                }
            } else {
                if (oldCount == maxQty) {
                    return -100;
                }
            }
        }
        return -1;
    }

    private int getCutPositionOutLimitCombo(ComboItem comboItem) {
        int mainOrderNumber = 1;
        int oldCount = 0;
        SparseArray<String> numberAndCutPositionMap = new SparseArray<>();
        OrderDetail currentMainOrderDetail = mSelectMealAdapter.getCurrentMainOrderDetail();
        if (currentMainOrderDetail != null) {
            int start_position = mSelectMealAdapter.getSelect_full_start_position();
            int end_position = mSelectMealAdapter.getSelect_full_end_position();
            for (int i = mOrderMealList.size() - 1; i >= 0; i--) {
                if (start_position <= i && i <= end_position) {
                    OrderDetail item = mOrderMealList.get(i);
                    if (item.getItemType() == 1) {
                        mainOrderNumber = item.getNumber();
                    }
                    if (item.getItemType() == 2 && item.getTopId() == comboItem.getComId()) {
                        //同一套餐下的子食品
                        String comboIdAndNumber = numberAndCutPositionMap.get((int) item.getTopId());
                        int cutPosition = i;
                        String value;
                        if (comboIdAndNumber != null) {
                            String[] splitStr = numberAndCutPositionMap.get((int) item.getTopId()).split("_");
                            if (item.isNew()) {
                                value = (Integer.parseInt(splitStr[0]) + item.getNumber()) + "_" + cutPosition;
                            } else {
                                //已下單不可替換刪除
                                if (splitStr.length > 1) {
                                    value = (Integer.parseInt(splitStr[0]) + item.getNumber()) + "_" + splitStr[1];
                                } else {
                                    value = (Integer.parseInt(splitStr[0]) + item.getNumber()) + "_";
                                }
                                oldCount++;
                            }
                        } else {
                            if (item.isNew()) {
                                value = item.getNumber() + "_" + cutPosition;
                            } else {
                                //已下單不可替換刪除
                                value = item.getNumber() + "_";
                                oldCount++;
                            }
                        }
                        numberAndCutPositionMap.put((int) item.getTopId(), value);
                    }
                }
            }
        }
        for (int i = 0; i < numberAndCutPositionMap.size(); i++) {
            String[] numberAndCutPositionStr = numberAndCutPositionMap.valueAt(i).split("_");
            int number = Integer.parseInt(numberAndCutPositionStr[0]);
            int maxQty = comboItem.getSelectQty() * mainOrderNumber;
            if (numberAndCutPositionStr.length > 1 && !TextUtils.isEmpty(numberAndCutPositionStr[1])) {
                int cutPosition = Integer.parseInt(numberAndCutPositionStr[1]);
                if (maxQty <= number && cutPosition < mOrderMealList.size()) {
                    return cutPosition;
                }
            } else {
                if (oldCount == maxQty) {
                    return -100;
                }
            }
        }
        return -1;
    }
    
    public void queryFoodListByParentId(long parentId) {
        mModel.queryDB_FoodList(parentId, BaseOrder.orderType)
                .compose(MyRxSchedulerUtils._io_main_f())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSingleSubscriber<List<Food>>(mErrorHandler) {

                    @Override
                    public void onSuccess(List<Food> foods) {
                        mFoodAdapter.resetSelect(-1, null);
                        if (foods != null) {
                            updateFoodData(foods, parentId);
                        }
//                        mRootView.showViewModeVisibility(MealConstant.food_ViewMode, MealConstant.food_group_ViewMode);
                    }
                });
    }

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

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

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

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

            }
        }
        return -1;
    }

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

    /**
     * 更新食品數據
     *
     * @param foodList
     * @param parentId
     */
    private void updateFoodData(List<Food> foodList, long parentId) {
        setTopId(foodList, parentId);
        setFoodComboListStatus(foodList);
        mFoodList.clear();
        mFoodList.addAll(foodList);
        //根据Item个数显示每一行的个数
        mRootView.setFoodRecycleSpanCount(mFoodList.size());
        mFoodAdapter.notifyDataSetChanged();
    }

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

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

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

    /**
     * 標識食品是否为组合食品
     *
     * @param foodList
     */
    private void setFoodComboListStatus(List<Food> foodList) {
        for (int i = 0; i < foodList.size(); i++) {
            Food datasBean = foodList.get(i);
            mModel.isComboFood(datasBean.getId())
                    .compose(MyRxSchedulerUtils._io_main_f())
                    .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                    .subscribe(new ErrorHandleSingleSubscriber<List<FoodCombo>>(mErrorHandler) {

                        @Override
                        public void onSuccess(List<FoodCombo> foodFoodComboList) {
                            if (foodFoodComboList.size() > 0) {
                                datasBean.setComboFood(true);
                            }
                        }
                    });
        }
    }

    /**
     * 細項默認選中
     *
     * @param modifierList
     */
    private void setModifierDefModifier(List<Modifier> modifierList) {
        String defmodifier = null;
        for (int i = 0; i < modifierList.size(); i++) {
            Modifier item = modifierList.get(i);
            if (item.getInvisible() != 2) {
                //過濾掉已暫停細項
                String modifier = item.getDefmodifier().trim();
                if (!TextUtils.isEmpty(modifier)) {
                    defmodifier = modifier + ",";
                }
            }
        }
        if (!TextUtils.isEmpty(defmodifier)) {
            if (defmodifier.startsWith(",")) {
                defmodifier = defmodifier.substring(1, defmodifier.length());
            }
            if (defmodifier.endsWith(",")) {
                defmodifier = defmodifier.substring(0, defmodifier.length() - 1);
            }
            String[] defmodifiers = defmodifier.split(",");
            for (int j = 0; j < defmodifiers.length; j++) {
                long def = Long.parseLong(defmodifiers[j]);
                for (int k = 0; k < modifierList.size(); k++) {
                    Modifier modifier = modifierList.get(k);
                    long mid = modifier.getMid();
                    if (def == mid) {
                        modifier.setDefmodifier("1");
                    } else {
                        if (!modifier.getDefmodifier().equals("1")) {
                            modifier.setDefmodifier("0");
                        }
                    }
                }
            }
        }
    }

    /**
     * 套餐默認選中
     *
     * @param comboItemList
     */
    private void setComboDefModifier(List<ComboItem> comboItemList) {
        String defmodifier = null;
        for (int i = 0; i < comboItemList.size(); i++) {
            ComboItem comboItem = comboItemList.get(i);
            if (comboItem.getInvisible() != 2) {
                //過濾掉已暫停食品
                String modifier = comboItem.getDefmodifier().trim();
                if (!TextUtils.isEmpty(modifier)) {
                    defmodifier = modifier + ",";
                }
            }
        }
        if (!TextUtils.isEmpty(defmodifier)) {
            if (defmodifier.startsWith(",")) {
                defmodifier = defmodifier.substring(1, defmodifier.length());
            }
            if (defmodifier.endsWith(",")) {
                defmodifier = defmodifier.substring(0, defmodifier.length() - 1);
            }
            String[] defmodifiers = defmodifier.split(",");
            for (int j = 0; j < defmodifiers.length; j++) {
                long def = Long.parseLong(defmodifiers[j]);
                for (int k = 0; k < comboItemList.size(); k++) {
                    ComboItem comboItem = comboItemList.get(k);
                    long fid = comboItem.getFid();
                    if (def == fid) {
                        comboItem.setDefmodifier("1");
                    } else {
                        if (!comboItem.getDefmodifier().equals("1")) {
                            comboItem.setDefmodifier("0");
                        }
                    }
                }
            }
        }
    }

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

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

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

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

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

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

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

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

    private void addFoodSoldoutCtrItem(List<SoldoutCtrFood> soldoutCtrFoods) {
        for (Food foodGroupBean : mFoodGroupList) {
            if (foodGroupBean.getInvisible() == 2) {
                SoldoutCtrFood soldoutCtrFood = new SoldoutCtrFood();
                soldoutCtrFood.setType((byte) FOOD_GROUP_TYPE);
                soldoutCtrFood.setStop(true);
                soldoutCtrFood.setFoodName(foodGroupBean.getFoodName());
                soldoutCtrFood.setFoodName1(foodGroupBean.getFoodName1());
                soldoutCtrFood.setFoodName2(foodGroupBean.getFoodName2());
                soldoutCtrFood.setFoodId(foodGroupBean.getId());
                if (!isContainFood(soldoutCtrFoods, foodGroupBean)) {
                    soldoutCtrFoods.add(soldoutCtrFood);
                }
            }
        }
        for (Food foodBean : mFoodList) {
            if (foodBean.getInvisible() == 2) {
                SoldoutCtrFood soldoutCtrFood = new SoldoutCtrFood();
                soldoutCtrFood.setType((byte) FOOD_TYPE);
                soldoutCtrFood.setStop(true);
                soldoutCtrFood.setFoodName(foodBean.getFoodName());
                soldoutCtrFood.setFoodName1(foodBean.getFoodName1());
                soldoutCtrFood.setFoodName2(foodBean.getFoodName2());
                soldoutCtrFood.setFoodId(foodBean.getId());
                soldoutCtrFoods.add(soldoutCtrFood);
                if (!isContainFood(soldoutCtrFoods, foodBean)) {
                    soldoutCtrFoods.add(soldoutCtrFood);
                }
            }
        }
    }

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

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

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

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

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

        int currentSelectNumber = 0;

        for (int i = 0; i < getNewOrderFoodLists().size(); i++) {
            OrderDetail orderFood = getNewOrderFoodLists().get(i);
            if (orderFood.getProductId() == foodBean.getId()) {
                currentSelectNumber += orderFood.getNumber();
            }
        }
        String User_Qty = foodBean.getMaxNumber();
        if (!User_Qty.equals("") && !User_Qty.equals("售罄") && !User_Qty.equals("暫停")) {
            int maxQty = Integer.parseInt(User_Qty);
            if (maxQty > 0) {
                int Currrent_OR_Qty = maxQty - currentSelectNumber;
                if (Currrent_OR_Qty < 1) {
                    foodBean.setCurrentMaxNumber("售罄");
                    return false;
                } else {
                    foodBean.setCurrentMaxNumber(Currrent_OR_Qty + "");
                }
            }
        }
        return true;
    }

    public void setComboItemMaxQty(ComboItem comboItem) {

        int currentSelectNumber = 0;

        for (int i = 0; i < getNewOrderFoodLists().size(); i++) {
            OrderDetail orderFood = getNewOrderFoodLists().get(i);
            if (orderFood.getProductId() == comboItem.getFid()) {
                currentSelectNumber += orderFood.getNumber();
            }
        }
        String User_Qty = comboItem.getMaxNumber();
        if (!User_Qty.equals("") && !User_Qty.equals("售罄") && !User_Qty.equals("暫停")) {
            int maxQty = Integer.parseInt(User_Qty);
            if (maxQty > 0) {
                int Currrent_OR_Qty = maxQty - currentSelectNumber;
                if (Currrent_OR_Qty < 1) {
                    comboItem.setCurrentMaxNumber("售罄");
                } else {
                    comboItem.setCurrentMaxNumber(Currrent_OR_Qty + "");
                }
            }
        }
        mComboAdapter.notifyDataSetChanged();
    }

    public void setModifierMaxQty(Modifier modfier) {

        int currentSelectNumber = 0;

        for (int i = 0; i < getNewOrderFoodLists().size(); i++) {
            OrderDetail orderFood = getNewOrderFoodLists().get(i);
            if (orderFood.getMid() == modfier.getMid()) {
                currentSelectNumber += orderFood.getNumber();
            }
        }
        String User_Qty = modfier.getMaxNumber();
        if (!User_Qty.equals("") && !User_Qty.equals("售罄") && !User_Qty.equals("暫停")) {
            int maxQty = Integer.parseInt(User_Qty);
            if (maxQty > 0) {
                int Currrent_OR_Qty = maxQty - currentSelectNumber;
                if (Currrent_OR_Qty < 1) {
                    modfier.setCurrentMaxNumber("售罄");
                } else {
                    modfier.setCurrentMaxNumber(Currrent_OR_Qty + "");
                }
            }
        }
        mModifierAdapter.notifyDataSetChanged();
    }

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

        if (init) {
            return true;
        }

        String User_Qty = foodBean.getCurrentMaxNumber();
        if (!TextUtils.isEmpty(User_Qty)) {
            String msg = "[" + foodBean.getFoodName() + "]" + LanguageUtils.get_language_system(mRootView.getActivity2(), "Comm.pause", "已暫停");
            CommonTipDialog.showSurpisedDialog(mRootView.getActivity2(), msg, null, null, null, null, null);
            return false;
        }
        return true;
    }

    private boolean foodConditionFilter(Food foodBean) {
        long Invisible = foodBean.getInvisible();
        if (Invisible == 2) {
            String msg = "[" + foodBean.getFoodName() + "]" + LanguageUtils.get_language_system(mRootView.getActivity2(), "Comm.pause", "已暫停");
            CommonTipDialog.showSurpisedDialog(mRootView.getActivity2(), msg, null, null, null, null, null);
            return false;
        }
        String User_Qty = foodBean.getCurrentMaxNumber();
        if (!TextUtils.isEmpty(User_Qty)) {
            if (User_Qty.equals("售罄") || User_Qty.equals("暫停")) {
                String msg = "[" + foodBean.getFoodName() + "]" + User_Qty;
                CommonTipDialog.showSurpisedDialog(mRootView.getActivity2(), msg, null, null, null, null, null);
                return false;
            }
        }
        if (!memberPointsCondition(foodBean.getPointsRedeem(), foodBean.getFoodName())) {
            return false;
        }
        return true;
    }

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

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

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