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

                int operatTtpe = 1;
                if (datasBean.isStop()) {
                    //恢復暫停數量
                    operatTtpe = 0;
                }
                String msg = LanguageUtils.get_language_system(mApplication, "whether.recover", "是否恢復[") + datasBean.getName() + "]";
                Class[] parameterTypes = {long.class, Long.class, Long.class, int.class, int.class};
                Object[] parameters = {datasBean.getId(), datasBean.getFoodId(), datasBean.getModifierId(), datasBean.getType(), operatTtpe};
                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)) {
                        showSoldoutNumberDialog(datasBean.getId(), null);
                    }
                }
            }
        });
    }

    @Subscriber(tag = MealConstant.SOLDOUT_MODIFIER)
    private void soldoutModifierItem(Modifier datasBean) {
        if (!modifierStopOpeart(datasBean)) {
            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;
                        int operatTtpe = 1;
                        if (datasBean.getInvisible() == 2) {
                            //恢復暫停數量
                            operatTtpe = 0;
                        }
                        //暂停或者售罄直接提示恢复
                        String msg = LanguageUtils.get_language_system(IActivity, "whether.recover", "是否恢復[") + datasBean.getFoodName() + "]";
                        Class[] parameterTypes = {long.class, Long.class, Long.class, int.class, int.class};
                        Object[] parameters = {csf.getId(), datasBean.getId(), null, 2, operatTtpe};
                        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;
                            int operatTtpe = 1;
                            if (datasBean.getInvisible() == 2) {
                                //恢復暫停數量
                                operatTtpe = 0;
                            }
                            //暂停或者售罄直接提示恢复
                            String msg = LanguageUtils.get_language_system(IActivity, "whether.recover", "是否恢復[") + datasBean.getModifierName() + "]";
                            Class[] parameterTypes = {long.class, Long.class, Long.class, int.class, int.class};
                            Object[] parameters = {csf.getId(), null, datasBean.getMid(), 3, operatTtpe};
                            CommonTipDialog.showDoubtDialog(IActivity, msg, SoldoutCtrlPresenter.class, this, "restoreSoldoutCtrl", parameterTypes, parameters);
                            break;
                        }
                    }
                }
            }
        }
        return isStopOpeart;
    }

    public void showSoldoutNumberDialog(Long foodId, Long modifierId) {
        //选择沽清的数量
        ChooseNumberDialog chooseNumberDialog = new ChooseNumberDialog(IActivity);
        chooseNumberDialog.setBackBtnText("暫停");
        chooseNumberDialog.builder();
        chooseNumberDialog.setOnClickListener(new ChooseNumberDialog.OnClickListener() {
            @Override
            public void onComfirmClick(String number) {
                insertSoldoutCtrl(foodId, modifierId, Integer.parseInt(number), Integer.parseInt(number) == 0 ? 0 : 1, foodId != null ? 2 : 3);
            }

            @Override
            public void onBackPage() {

            }
        });
        chooseNumberDialog.setType(2);
        chooseNumberDialog.setCancelable(true);
        chooseNumberDialog.show();
    }

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

    /**
     * 設置食品沽清數據
     */
    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();
    }

    private void setFoodStopStatus(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());
                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);
            }
        }
    }

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

                            setFoodStopStatus(soldoutCtrFoods);
                            setFoodSoldoutCtrData(soldoutCtrFoods);

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

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

                                filterSlodoutData(false);

                                //更新細項沽清數據
                                IActivity.setFineItemSlodoutListFull(mCurrentSlodoutFoodList_Full);

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

                                //更新細項沽清數據
                                IActivity.setFineItemSlodoutListFull(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;
                            }
                            if (operatTtpe == 0) {
                                //暫停操作需要更新食品表狀態
                                switch (type) {
                                    case 1:
                                    case 2:
                                        //更新食品狀態
                                        FoodDaoUtils foodDao = new FoodDaoUtils(IActivity);
                                        Food food = foodDao.queryFoodByFidQueryBuilder(foodId);
                                        food.setInvisible(2);
                                        boolean status = foodDao.updateFood(food);
                                        if (status) {
                                            if (food.getParentId() == 0) {
                                                updateFoodGroup();
                                            } else {
                                                mAllFoodList = mModel.queryDB_AllFoodList();
                                                changedMealByParentId(currentParentId);
                                            }
                                        }
//                                        downFoodList();
                                        break;
                                    case 3:
                                        //更新細項狀態
                                        downFoodModifier();
                                        break;
                                }
                            } else {
                            }
                            //重新获取沽清数据
                            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
     * @param type       恢復類型:1=食品組;1=食品;1=細項;
     * @param operatTtpe 0= 暂停恢復，1=恢復食品沽清数量
     */
    public void restoreSoldoutCtrl(long id, Long foodId, Long modifierId, int type, int operatTtpe) {
        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;
                            if (operatTtpe == 0) {
                                //暫停恢復需要更新食品表狀態
                                switch (type) {
                                    case 1:
                                    case 2:
                                        //更新食品狀態
                                        FoodDaoUtils foodDao = new FoodDaoUtils(IActivity);
                                        Food food = foodDao.queryFoodByFidQueryBuilder(foodId);
                                        if (food != null) {
                                            food.setInvisible(2);
                                            boolean status = foodDao.updateFood(food);
                                            if (status) {
                                                if (food.getParentId() == 0) {
                                                    updateFoodGroup();
                                                } else {
                                                    mAllFoodList = mModel.queryDB_AllFoodList();
                                                    changedMealByParentId(currentParentId);
                                                }
                                            }
                                        }
                                        break;
                                    case 3:
                                        //更新細項狀態
                                        ModifierDaoUtils modifierDaoUtils = new ModifierDaoUtils(mApplication);
                                        Modifier modifier = modifierDaoUtils.queryModifierByQueryBuilder(modifierId);
                                        if (modifier != null) {
                                            modifier.setInvisible(2);
                                            boolean status = modifierDaoUtils.updateModifier(modifier);
                                            if (status) {

                                            }
                                        }
//                                        downFoodModifier();
                                        break;
                                }
                            } else {
                            }
                            //重新获取沽清数据
                            getCurrentSoldoutFood();
                        } else {
                            mRootView.showMessage(LanguageUtils.get_language_system(mApplication, "recovery.failure", "恢復失敗!"));
                        }
                    }
                });
    }

    public void downFoodList() {
        int restaurantId = GsaCloudApplication.getRestaurantId(mApplication);
        mModel.downFoodList(restaurantId)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<FoodBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull FoodBean foodBean) {
                        if (foodBean != null && foodBean.isSuccess()) {
                            if (foodBean.getData() != null) {
                                FoodDaoUtils foodDao = new FoodDaoUtils(IActivity);
                                foodDao.deleteAll();
                                boolean status = foodDao.insertMultFood(foodBean.getData());
                                if (status) {
                                    //更新表數據成功
                                    changedMealByParentId(currentParentId);
                                    //重新获取沽清数据
                                    getCurrentSoldoutFood();
                                }
                            }
                        } else {
                        }
                    }
                });
    }

    public void downFoodModifier() {
        int restaurantId = GsaCloudApplication.getRestaurantId(IActivity);
        mModel.downFoodModifier(restaurantId)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null) {
                                List<FoodModifier> foodModifierList = JsonUtils.parseArray(info.getData(), FoodModifier.class);
                                if (foodModifierList != null && foodModifierList.size() > 0) {
                                    FoodModifierDaoUtils foodModifierDao = new FoodModifierDaoUtils(IActivity);
                                    foodModifierDao.deleteAll();
                                    boolean status = foodModifierDao.insertMultFoodModifier(foodModifierList);
                                    if (status) {
                                        //重新获取沽清数据
                                        getCurrentSoldoutFood();
                                    }
                                }
                            }
                        }
                    }
                });
    }

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