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

    //记录已沽清选中的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;


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

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

                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)) {
                        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 (!TextUtils.isEmpty(csf.getQtyName())) {
                        isStopOpeart = true;
                        //暂停或者售罄直接提示恢复
                        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 (!TextUtils.isEmpty(csf.getQtyName())) {
                            isStopOpeart = true;
                            //暂停或者售罄直接提示恢复
                            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 showSoldoutNumberDialog(Long foodId, Long modifierId) {
        //选择沽清的数量
        ChooseNumberDialog chooseNumberDialog = new ChooseNumberDialog(IActivity);
        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);
            }

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

    public void changedMealByParentId(long 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() {
        clearFoodSoldoutCtrData();
        for (SoldoutCtrFood scc : mCurrentSlodoutFoodList_Full) {
            for (Food foodGroupBean : mFoodGroupList) {
                if (scc.getType() == FOOD_GROUP_TYPE && scc.getFoodId() != null && foodGroupBean.getId() != null && foodGroupBean.getId().equals(scc.getFoodId())) {
                    String qty = scc.getQtyName();
                    foodGroupBean.setMaxNumber(qty);
                    foodGroupBean.setCurrentMaxNumber(qty);
                }
            }
            for (Food foodBean : mFoodList) {
                if (scc.getType() == FOOD_TYPE && scc.getFoodId() != null && foodBean.getId() != null && foodBean.getId().equals(scc.getFoodId())) {
                    String qty = scc.getQtyName();
                    foodBean.setMaxNumber(qty);
                    foodBean.setCurrentMaxNumber(qty);
                }
            }
        }
        IActivity.getFoodGroupAdapter().notifyDataSetChanged();
        mFoodAdapter.notifyDataSetChanged();
    }

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

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

    /**
     * 插入沽清控制
     *
     * @param foodId
     * @param modifierId
     * @param remainingNumber
     * @param operatTtpe      0= 暂停，1=改变食品沽清数量
     */
    public void insertSoldoutCtrl(Long foodId, Long modifierId, int remainingNumber, int operatTtpe) {
        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)
                .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", "沽清失敗!"));
                        }
                    }
                });
    }

    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", "恢復失敗!"));
                        }
                    }
                });
    }

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