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

import android.app.Application;
import android.text.TextUtils;

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.FoodBean;
import com.gingersoft.gsa.cloud.base.common.bean.TableBean;
import com.gingersoft.gsa.cloud.base.utils.JsonUtils;
import com.gingersoft.gsa.cloud.base.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.base.utils.VibratorUtils;
import com.gingersoft.gsa.cloud.base.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.constans.MealConstant;
import com.gingersoft.gsa.cloud.database.bean.ComboItem;
import com.gingersoft.gsa.cloud.database.bean.Food;
import com.gingersoft.gsa.cloud.database.bean.FoodModifier;
import com.gingersoft.gsa.cloud.database.bean.Modifier;
import com.gingersoft.gsa.cloud.database.utils.FoodDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.FoodModifierDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.ModifierDaoUtils;
import com.gingersoft.gsa.cloud.table.mvp.contract.SoldoutCtrlContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.SoldoutCtrFood;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.request.SoldoutRequest;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.SoldoutCtrlActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.CurrentSlodoutFoodAdapter;
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.widget.ChooseNumberDialog;
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.RxLifecycleUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

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

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.RequestBody;

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/22/2020 10:39
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
@ActivityScope
public class SoldoutCtrlPresenter extends BasePresenter<SoldoutCtrlContract.Model, SoldoutCtrlContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private SoldoutCtrlActivity IActivity;

    private CurrentSlodoutFoodAdapter mCurrentSlodoutFoodAdapter;
    private FoodAdapter mFoodAdapter;

    //所有沽清数据
    private List<SoldoutCtrFood> mCurrentSlodoutFoodList_Full = new ArrayList<>();
    //当前沽清类型
    private List<SoldoutCtrFood> mCurrentSlodoutFoodList = new ArrayList<>();
    //食品組
    private List<Food> mFoodGroupList = new ArrayList<>();
    //當前食品組下食品
    private List<Food> mFoodList = new ArrayList<>();
    //所有食品數據
    private List<Food> mAllFoodList = new ArrayList<>();

    //记录已沽清选中的Item（默认第一个）
    private int mCurrentSlodoutFoodPosition_FoodKind = 0;
    private int mCurrentSlodoutFoodPosition_Food = 0;
    private int mCurrentSlodoutFoodPosition_FoodFine = 0;

    //记录种类上次选中的食品种类
    private int mFoodKindLastPosition = -1;

    //当前操作类型({0=暂停，1=沽清}，2=恢复)
    private int mOperatTtpe = -1;

    private boolean isInsertSoldoutOperat = false;

    private long currentParentId;

    @Inject
    public SoldoutCtrlPresenter(SoldoutCtrlContract.Model model, SoldoutCtrlContract.View rootView) {
        super(model, rootView);
        this.IActivity = (SoldoutCtrlActivity) rootView;
        this.mAllFoodList = mModel.queryDB_AllFoodList();
    }

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

    public void initAdapter() {
        if (mCurrentSlodoutFoodAdapter == null) {
            mCurrentSlodoutFoodAdapter = new CurrentSlodoutFoodAdapter(mApplication, mCurrentSlodoutFoodList);
            mRootView.setCurrentSoldoutFoodAdapter(mCurrentSlodoutFoodAdapter);
        }
        if (mFoodAdapter == null) {
            mFoodAdapter = new FoodAdapter(mApplication, mFoodList, 2);
            mRootView.setFoodAdapter(mFoodAdapter);
        }
    }

    public void initFoodListener() {
        mCurrentSlodoutFoodAdapter.setOnItemClickListener(new CurrentSlodoutFoodAdapter.OnItemClickListener() {

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

                VibratorUtils.pressButtonSound(mApplication);

                if (mCurrentSlodoutFoodList.size() < 1) {
                    return;
                }

                switch (mRootView.getSoldoutType()) {
                    case FOOD_GROUP_TYPE:
                        mCurrentSlodoutFoodPosition_FoodKind = position;
                        break;
                    case FOOD_TYPE:
                        mCurrentSlodoutFoodPosition_Food = position;
                        break;
                    case MODIFIER_TYPE:
                        mCurrentSlodoutFoodPosition_FoodFine = position;
                        break;
                    default:
                        break;
                }

                mCurrentSlodoutFoodAdapter.setSelectPosition(position);
                mCurrentSlodoutFoodAdapter.notifyDataSetChanged();

                if (datasBean.isStop()) {
                    long id ;
                    if (datasBean.getType() == MODIFIER_TYPE) {
                        id = datasBean.getModifierId();
                    } else {
                        id = datasBean.getFoodId();
                    }                    //恢復暫停數量
                    String msg = LanguageUtils.get_language_system(IActivity, "whether.recover", "是否恢復[") + datasBean.getFoodName() + "]";
                    Class[] parameterTypes = {Long.class, int.class, int.class};
                    Object[] parameters = {id, datasBean.getType(), 0};
                    CommonTipDialog.showDoubtDialog(IActivity, msg, SoldoutCtrlPresenter.class, SoldoutCtrlPresenter.this, "updateInvisible", parameterTypes, parameters);
                } else {
                    //恢復沽清數量
                    String msg = LanguageUtils.get_language_system(mApplication, "whether.recover", "是否恢復[") + datasBean.getName() + "]";
                    Class[] parameterTypes = {long.class};
                    Object[] parameters = {datasBean.getId()};
                    CommonTipDialog.showDoubtDialog(IActivity, msg, SoldoutCtrlPresenter.class, SoldoutCtrlPresenter.this, "restoreSoldoutCtrl", parameterTypes, parameters);
                }

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

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

                VibratorUtils.pressButtonSound(mApplication);

                if (mRootView.getSoldoutType() == FOOD_TYPE) {
                    if (!foodStopOpeart(datasBean)) {
                        IActivity.showSoldoutNumberDialog(datasBean.getId(), null);
                    }
                } else if (mRootView.getSoldoutType() == MODIFIER_TYPE) {
                    IActivity.showModfierLayout(datasBean.getId());
                }
            }
        });
    }

    @Subscriber(tag = MealConstant.SOLDOUT_MODIFIER)
    private void soldoutModifierItem(Modifier datasBean) {
        if (!modifierStopOpeart(datasBean)) {
            IActivity.showSoldoutNumberDialog(null, datasBean.getMid());
        }
    }

    public boolean foodStopOpeart(Food datasBean) {
        boolean isStopOpeart = false;
        if (mCurrentSlodoutFoodList_Full != null) {
            for (SoldoutCtrFood csf : mCurrentSlodoutFoodList_Full) {
                if (csf.getFoodId() != null && datasBean.getId() != null &&
                        csf.getFoodId().equals(datasBean.getId()) && csf.getType() == FOOD_TYPE) {
                    if (datasBean.getInvisible() == 2 || !TextUtils.isEmpty(csf.getQtyName())) {
                        isStopOpeart = true;
                        if (datasBean.getInvisible() == 2) {
                            //恢復暫停數量
                            String msg = LanguageUtils.get_language_system(IActivity, "whether.recover", "是否恢復[") + datasBean.getFoodName() + "]";
                            Class[] parameterTypes = {Long.class, int.class, int.class};
                            Object[] parameters = {datasBean.getId(), 2, 0};
                            CommonTipDialog.showDoubtDialog(IActivity, msg, SoldoutCtrlPresenter.class, this, "updateInvisible", parameterTypes, parameters);
                        } else {
                            //暂停或者售罄直接提示恢复
                            String msg = LanguageUtils.get_language_system(IActivity, "whether.recover", "是否恢復[") + datasBean.getFoodName() + "]";
                            Class[] parameterTypes = {long.class};
                            Object[] parameters = {csf.getId()};
                            CommonTipDialog.showDoubtDialog(IActivity, msg, SoldoutCtrlPresenter.class, this, "restoreSoldoutCtrl", parameterTypes, parameters);
                        }
                        break;
                    }
                }
            }
        }
        return isStopOpeart;
    }

    private boolean modifierStopOpeart(Modifier datasBean) {
        boolean isStopOpeart = false;
        if (mCurrentSlodoutFoodList_Full != null) {
            for (SoldoutCtrFood csf : mCurrentSlodoutFoodList_Full) {
                if (csf.getModifierId() != null) {
                    if (csf.getModifierId() == datasBean.getMid() && csf.getType() == MODIFIER_TYPE) {
                        if (datasBean.getInvisible() == 2 || !TextUtils.isEmpty(csf.getQtyName())) {
                            isStopOpeart = true;
                            if (datasBean.getInvisible() == 2) {
                                //恢復暫停數量
                                String msg = LanguageUtils.get_language_system(IActivity, "whether.recover", "是否恢復[") + datasBean.getModifierName() + "]";
                                Class[] parameterTypes = {Long.class, int.class, int.class};
                                Object[] parameters = {datasBean.getMid(), 3, 0};
                                CommonTipDialog.showDoubtDialog(IActivity, msg, SoldoutCtrlPresenter.class, this, "updateInvisible", parameterTypes, parameters);
                            } else {
                                String msg = LanguageUtils.get_language_system(IActivity, "whether.recover", "是否恢復[") + datasBean.getModifierName() + "]";
                                Class[] parameterTypes = {long.class};
                                Object[] parameters = {csf.getId()};
                                CommonTipDialog.showDoubtDialog(IActivity, msg, SoldoutCtrlPresenter.class, this, "restoreSoldoutCtrl", parameterTypes, parameters);
                            }
                            break;
                        }
                    }
                }
            }
        }
        return isStopOpeart;
    }


    public void initFoodData() {
        List<Food> foodGroupList = mModel.queryDB_FoodGroupList();
        if (foodGroupList != null && foodGroupList.size() > 0) {
            mFoodGroupList.addAll(foodGroupList);
            //默認選中第一組
            mFoodGroupList.get(0).setSelected(true);
            IActivity.initFoodGroupView(mFoodGroupList);
            changedMealByParentId(mFoodGroupList.get(0).getId());
        }
        getCurrentSoldoutFood();
    }

    private void updateFoodGroup() {
        List<Food> foodGroupList = mModel.queryDB_FoodGroupList();
        if (foodGroupList != null && foodGroupList.size() > 0) {
            if (mFoodGroupList.size() > 0) {
                mFoodGroupList.clear();
            }
            mFoodGroupList.addAll(foodGroupList);
            IActivity.getFoodGroupAdapter().notifyDataSetChanged();
        }
    }

    public void changedMealByParentId(long parentId) {
        this.currentParentId = parentId;
        List<Food> foodList = mModel.queryDB_FoodList(parentId);
        mFoodAdapter.resetSelect(-1, null);
        if (foodList != null) {
            updateFoodData(foodList);
        }
    }

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

    /**
     * 更新沽清數據
     *
     * @param soldoutCtrFoods
     */
    public void updateFoodSoldoutCtrData(List<SoldoutCtrFood> soldoutCtrFoods) {
        addFoodSoldoutCtrItem(soldoutCtrFoods);
        setFoodSoldoutCtrData(soldoutCtrFoods);
    }

    /**
     * 設置食品沽清數據
     */
    public void setFoodSoldoutCtrData(List<SoldoutCtrFood> soldoutCtrFoods) {
        clearFoodSoldoutCtrData();
        for (SoldoutCtrFood scc : soldoutCtrFoods) {
            for (Food foodGroupBean : mFoodGroupList) {
                if (scc.getType() == FOOD_GROUP_TYPE && scc.getFoodId() != null && foodGroupBean.getId() != null && foodGroupBean.getId().equals(scc.getFoodId())) {
                    String qtyName;
                    if (foodGroupBean.getInvisible() == 2) {
                        qtyName = "暫停";
                        scc.setStop(true);
                        foodGroupBean.setMaxNumber(qtyName);
                        foodGroupBean.setCurrentMaxNumber(qtyName);
                    } else {
                        qtyName = scc.getQtyName();
                        scc.setStop(false);
                        foodGroupBean.setMaxNumber(qtyName);
                        foodGroupBean.setCurrentMaxNumber(qtyName);
                    }
                }
            }
            //設置當前選中食品組下食品沽清
            for (Food foodBean : mFoodList) {
                if (scc.getType() == FOOD_TYPE && scc.getFoodId() != null && foodBean.getId() != null && foodBean.getId().equals(scc.getFoodId())) {
                    String qtyName;
                    if (foodBean.getInvisible() == 2) {
                        qtyName = "暫停";
                        scc.setStop(true);
                        foodBean.setMaxNumber(qtyName);
                        foodBean.setCurrentMaxNumber(qtyName);
                    } else {
                        qtyName = scc.getQtyName();
                        scc.setStop(false);
                        foodBean.setMaxNumber(qtyName);
                        foodBean.setCurrentMaxNumber(qtyName);
                    }
                }
            }
            //設置未選中食品組下食品沽清
            for (Food foodBean : mAllFoodList) {
                if (scc.getType() == FOOD_TYPE && scc.getFoodId() != null && foodBean.getId() != null && foodBean.getId().equals(scc.getFoodId())) {
                    if (foodBean.getInvisible() == 2) {
                        scc.setStop(true);
                    } else {
                        scc.setStop(false);
                    }
                }
            }
        }
        IActivity.getFoodGroupAdapter().notifyDataSetChanged();
        mFoodAdapter.notifyDataSetChanged();
    }

    /**
     * 添加食品組 食品沽清項
     *
     * @param soldoutCtrFoods
     */
    private void addFoodSoldoutCtrItem(List<SoldoutCtrFood> soldoutCtrFoods) {
        //先刪除已暫停的沽清項 防止重複
        for (int i = soldoutCtrFoods.size() - 1; i >= 0; i--) {
            if (soldoutCtrFoods.get(i).isStop()) {
                soldoutCtrFoods.remove(i);
            }
        }
        //添加暫停沽清項
        for (Food foodGroupBean : mFoodGroupList) {
            if (foodGroupBean.getInvisible() == 2 && foodGroupBean.getParentId() == 0) {
                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());
                soldoutCtrFoods.add(soldoutCtrFood);
            }
        }
        for (Food foodBean : mAllFoodList) {
            if (foodBean.getInvisible() == 2 && foodBean.getParentId() != 0) {
                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);
            }
        }
    }

    private void clearFoodSoldoutCtrData() {
        for (Food foodGroupBean : mFoodGroupList) {
            foodGroupBean.setMaxNumber("");
            foodGroupBean.setCurrentMaxNumber("");
        }
        for (Food foodBean : mFoodList) {
            foodBean.setMaxNumber("");
            foodBean.setCurrentMaxNumber("");
        }
    }

    /**
     * 过滤沽清数据
     */
    public void filterSlodoutData(boolean init) {
        if (mCurrentSlodoutFoodList_Full == null)
            return;
        if (mCurrentSlodoutFoodList.size() > 0)
            mCurrentSlodoutFoodList.clear();
        switch (mRootView.getSoldoutType()) {
            case FOOD_GROUP_TYPE:
                for (SoldoutCtrFood scc : mCurrentSlodoutFoodList_Full) {
                    if (scc.getType() == FOOD_GROUP_TYPE) {
                        mCurrentSlodoutFoodList.add(scc);
                    }
                }
                break;
            case FOOD_TYPE:
                for (SoldoutCtrFood scc : mCurrentSlodoutFoodList_Full) {
                    if (scc.getType() == FOOD_TYPE) {
                        mCurrentSlodoutFoodList.add(scc);
                    }
                }
                break;
            case MODIFIER_TYPE:
                for (SoldoutCtrFood scc : mCurrentSlodoutFoodList_Full) {
                    if (scc.getType() == MODIFIER_TYPE) {
                        mCurrentSlodoutFoodList.add(scc);
                    }
                }
                break;
            default:
                break;
        }
        if (!init) {
            //沽清完重新获取数据
            if (isInsertSoldoutOperat) {
                isInsertSoldoutOperat = false;
                mCurrentSlodoutFoodAdapter.setSelectPosition(mCurrentSlodoutFoodList.size() - 1);
                mRootView.getRecycleCurrentSoldoutFood().smoothScrollToPosition(mCurrentSlodoutFoodList.size() - 1);
            } else {
                switch (mRootView.getSoldoutType()) {
                    case FOOD_GROUP_TYPE:
                        if (mCurrentSlodoutFoodPosition_FoodKind != 0 && mCurrentSlodoutFoodList.size() > 1) {
                            if (mOperatTtpe != -1) {
                                if (mOperatTtpe == 0 || mOperatTtpe == 1) {
                                    mCurrentSlodoutFoodPosition_FoodKind = mCurrentSlodoutFoodList.size() - 1; //暂停、沽清选中当前操作的
                                } else {
                                    mCurrentSlodoutFoodPosition_FoodKind--; //恢复选中上面一个
                                }
                            }
                        }
                        mCurrentSlodoutFoodAdapter.setSelectPosition(mCurrentSlodoutFoodPosition_FoodKind);
                        break;
                    case FOOD_TYPE:
                        if (mCurrentSlodoutFoodPosition_Food != 0 && mCurrentSlodoutFoodList.size() > 1) {
                            if (mOperatTtpe != -1) {
                                if (mOperatTtpe == 0 || mOperatTtpe == 1) {
                                    mCurrentSlodoutFoodPosition_Food = mCurrentSlodoutFoodList.size() - 1; //暂停、沽清选中当前操作的
                                } else {
                                    mCurrentSlodoutFoodPosition_Food--; //恢复选中上面一个
                                }
                            }
                        }
                        mCurrentSlodoutFoodAdapter.setSelectPosition(mCurrentSlodoutFoodPosition_Food);
                        break;
                    case MODIFIER_TYPE:
                        if (mCurrentSlodoutFoodPosition_FoodFine != 0 && mCurrentSlodoutFoodList.size() > 1) {
                            if (mOperatTtpe != -1) {
                                if (mOperatTtpe == 0 || mOperatTtpe == 1) {
                                    mCurrentSlodoutFoodPosition_FoodFine = mCurrentSlodoutFoodList.size() - 1; //暂停、沽清选中当前操作的
                                } else {
                                    mCurrentSlodoutFoodPosition_FoodFine--; //恢复选中上面一个
                                }
                            }
                        }
                        mCurrentSlodoutFoodAdapter.setSelectPosition(mCurrentSlodoutFoodPosition_FoodFine);
                        break;
                }
            }
        }
        mCurrentSlodoutFoodAdapter.notifyDataSetChanged();
    }

    public void getCurrentSoldoutFood() {
        long restaurantId = GsaCloudApplication.getRestaurantId(mApplication);
        RequestBody requestBody = new FormBody.Builder()
                .add("restaurantId", String.valueOf(restaurantId))
                .build();
        mModel.getCurrentSoldoutFood(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {


                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess() && info.getData() != null) {

                            List<SoldoutCtrFood> soldoutCtrFoods = JsonUtils.parseArray(info.getData(), SoldoutCtrFood.class);

                            updateFoodSoldoutCtrData(soldoutCtrFoods);

                            if (soldoutCtrFoods != null && soldoutCtrFoods.size() > 0) {

                                if (mCurrentSlodoutFoodList_Full.size() > 0) {
                                    mCurrentSlodoutFoodList_Full.clear();
                                }
                                mCurrentSlodoutFoodList_Full.addAll(soldoutCtrFoods);

                                //更新細項沽清數據
                                IActivity.setFineItemSoldoutListFull(null, mCurrentSlodoutFoodList_Full);

                            } else {
                                if (mCurrentSlodoutFoodList_Full.size() > 0) {
                                    mCurrentSlodoutFoodList_Full.clear();
                                }

                                //更新細項沽清數據
                                IActivity.setFineItemSoldoutListFull(null, mCurrentSlodoutFoodList_Full);

                                if (mCurrentSlodoutFoodList.size() > 0) {
                                    mCurrentSlodoutFoodList.clear();
                                }
                                mCurrentSlodoutFoodAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                });
    }

    /**
     * 插入沽清控制
     *
     * @param foodId
     * @param modifierId
     * @param remainingNumber
     * @param operatTtpe      0= 暂停，1=改变食品沽清数量
     * @param type            恢復類型:1=食品組;2=食品;3=細項;
     */
    public void insertSoldoutCtrl(Long foodId, Long modifierId, int remainingNumber, int operatTtpe, int type) {
        SoldoutRequest.Insert request = getInsertSoldoutRequest(foodId, modifierId, remainingNumber);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(request));
        String json = GsonUtils.GsonString(request);
        mModel.insertSoldoutCtrl(requestBody, operatTtpe, type)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            //记录操作类型
                            mOperatTtpe = operatTtpe;
                            if (mOperatTtpe == 1) {
                                isInsertSoldoutOperat = true;
                            }
                            //重新获取沽清数据
                            getCurrentSoldoutFood();
                        } else {
                            if (operatTtpe == 0)
                                mRootView.showMessage(LanguageUtils.get_language_system(mApplication, "pause.failed", "暫停失敗!"));
                            else
                                mRootView.showMessage(LanguageUtils.get_language_system(mApplication, "soldout.failure", "沽清失敗!"));
                        }
                    }
                });
    }

    /**
     * 恢復沽清
     *
     * @param id 明細ID
     */
    public void restoreSoldoutCtrl(long id) {
        SoldoutRequest.update request = getDeleteRequest(id);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(request));
        String json = GsonUtils.GsonString(request);
        mModel.restoreSoldoutCtrl(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            //记录恢复操作类型
                            mOperatTtpe = 2;
                            //重新获取沽清数据
                            getCurrentSoldoutFood();
                        } else {
                            mRootView.showMessage(LanguageUtils.get_language_system(mApplication, "recovery.failure", "恢復失敗!"));
                        }
                    }
                });
    }

    /**
     * 更新食品組，食品，細項狀態
     *
     * @param id        1食品組 2食品 3 細項;
     * @param type      類型:1=食品組;2=食品;3=細項;
     * @param invisible 0=顯示, 1=隱藏, 2=暫停
     */
    public void updateInvisible(Long id, int type, int invisible) {
        RequestBody requestBody = new FormBody.Builder()
                .add("id", String.valueOf(id))
                .add("type", String.valueOf(type))
                .add("invisible", String.valueOf(invisible))
                .build();
        mModel.updateInvisible(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            //记录恢复操作类型
                            mOperatTtpe = 2;
                            //暫停恢復需要更新食品表狀態
                            switch (type) {
                                case 1:
                                case 2:
                                    //更新食品狀態
                                    FoodDaoUtils foodDao = new FoodDaoUtils(IActivity);
                                    Food food = foodDao.queryFoodByFidQueryBuilder(id);
                                    if (food != null) {
                                        food.setInvisible(invisible);
                                        boolean status = foodDao.updateFood(food);
                                        if (status) {
                                            if (food.getParentId() == 0) {
                                                updateFoodGroup();
                                            } else {
                                                mAllFoodList = mModel.queryDB_AllFoodList();
                                                changedMealByParentId(currentParentId);
                                            }
                                            updateFoodSoldoutCtrData(mCurrentSlodoutFoodList_Full);
                                            filterSlodoutData(false);
                                        }
                                    }
                                    break;
                                case 3:
                                    //更新細項狀態
                                    ModifierDaoUtils modifierDaoUtils = new ModifierDaoUtils(mApplication);
                                    Modifier modifier = modifierDaoUtils.queryModifierByQueryBuilder(id);
                                    if (modifier != null) {
                                        modifier.setInvisible(invisible);
                                        boolean status = modifierDaoUtils.updateModifier(modifier);
                                        if (status) {
                                            //更新細項沽清數據
                                            IActivity.setFineItemSoldoutListFull(null, mCurrentSlodoutFoodList_Full);
                                        }
                                    }
                                    break;
                            }
                            //重新获取沽清数据
//                            getCurrentSoldoutFood();
                        } else {
                            mRootView.showMessage(LanguageUtils.get_language_system(mApplication, "recovery.failure", "恢復失敗!"));
                        }
                    }
                });
    }

    private SoldoutRequest.Insert getInsertSoldoutRequest(Long foodId, Long modifierId, int remainingNumber) {
        SoldoutRequest.Insert request = new SoldoutRequest.Insert();
        request.setBrandId(GsaCloudApplication.getBrandId(mApplication));
        request.setRestaurantId(GsaCloudApplication.getRestaurantId(mApplication));
        if (foodId != null) {
            request.setFoodId(foodId);
        }
        if (modifierId != null) {
            request.setModifierId(modifierId);
        }
        request.setType(mRootView.getSoldoutType());
        request.setRemainingNumber(remainingNumber);
        request.setUid(GsaCloudApplication.getMemberId(mApplication));
        return request;
    }

    private SoldoutRequest.update getDeleteRequest(long id) {
        SoldoutRequest.update request = new SoldoutRequest.update();
        request.setId(id);
        request.setDeletes(1);
        return request;
    }

    public List<SoldoutCtrFood> getCurrentSlodoutFoodList_Full() {
        return mCurrentSlodoutFoodList_Full;
    }

    public CurrentSlodoutFoodAdapter getCurrentSlodoutFoodAdapter() {
        return mCurrentSlodoutFoodAdapter;
    }
}
