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

import android.app.Application;

import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.base.utils.JsonUtils;
import com.gingersoft.gsa.cloud.table.mvp.contract.OrderCenterContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.OrderDetailItem;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.orderManager.OrderCenterActivity;
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 com.scwang.smartrefresh.layout.api.RefreshLayout;

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;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 03/13/2020 14:28
 * <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 OrderCenterPresenter extends BasePresenter<OrderCenterContract.Model, OrderCenterContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private OrderCenterActivity IActivity;
    //是否可以繼續上拉刷新
    private boolean noMoreData = false;


    @Inject
    public OrderCenterPresenter(OrderCenterContract.Model model, OrderCenterContract.View rootView) {
        super(model, rootView);
        this.IActivity = (OrderCenterActivity) rootView;

    }

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

    /***
     * 獲取訂單列表
     * @param orderType
     * @param pageIndex
     * @param pageSize
     * @param refreshLayout
     * @param isLoadMore
     */
    public void loadOrderList(String orderType, int pageIndex, int pageSize, RefreshLayout refreshLayout, boolean isLoadMore) {
        int restaurantId = GsaCloudApplication.getRestaurantId();
        if (pageIndex != 0) {
            //根據數據庫下標分頁
            pageIndex = pageIndex * pageSize;
        }
        mModel.loadOrderList(restaurantId, orderType, pageIndex, pageSize)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    if (refreshLayout == null) {
                        mRootView.showLoading(null);
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onSubscribe(Disposable d) {
                        super.onSubscribe(d);
                        if (!isLoadMore) {
                            //初始化或下拉刷新,重置上拉加載標誌
                            noMoreData = false;
                        }
                    }

                    @Override
                    public void onNext(@NonNull BaseResult result) {
                        if (result.isSuccess()) {
                            if (result.getData() != null) {
                                List<OrderDetailItem> orderItemList = JsonUtils.parseArray(result.getData(), OrderDetailItem.class);
                                if (orderItemList != null && orderItemList.size() > 0) {
                                    if (!noMoreData) {
                                        mRootView.returnOrderItemList(orderItemList);
                                        //每次更新完數據，頁碼+1
                                        mRootView.setPageIndex(mRootView.getPageIndex() + 1);
                                    }
                                    if (orderItemList.size() < pageSize) {
                                        //沒有更多數據不能上拉刷新
                                        noMoreData = true;
                                    } else {
                                        noMoreData = false;
                                    }
                                } else {
                                    if (!noMoreData) {
                                        mRootView.getCurrentOrderFragment().showEmptyView(true, 0, null);
                                    }
                                }
                            } else {
                                mRootView.getCurrentOrderFragment().showEmptyView(true, 0, null);
                            }
                        } else {
                            mRootView.getCurrentOrderFragment().showEmptyView(false, 0, null);
                        }
                        resetRefreshLayout(noMoreData);
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.getCurrentOrderFragment().showEmptyView(false, 0, t);
                        resetRefreshLayout(false);
                    }

                    private void resetRefreshLayout(boolean noMoreData) {
                        if (refreshLayout != null) {
                            if (isLoadMore) {
                                if (noMoreData) {
                                    refreshLayout.setNoMoreData(true);
                                }
                                refreshLayout.finishLoadMore();
                            } else {
                                refreshLayout.finishRefresh();
                                refreshLayout.resetNoMoreData();
                            }
                        }
                    }
                });
    }

    /**
     * 取消訂單
     *
     * @param orderId
     */
    public void cancelOrder(long orderId, String orderType) {
        int restaurantId = GsaCloudApplication.getRestaurantId();
        mModel.cancelOrder(orderId, restaurantId, orderType)
                .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 result) {
                        if (result.isSuccess()) {
                            if (result.getData() != null) {
                                List<OrderDetailItem> orderItemList = JsonUtils.parseArray(result.getData(), OrderDetailItem.class);
                                if (orderItemList.size() > 0) {
                                    mRootView.setPageIndex(0);
                                    mRootView.returnOrderItemList(orderItemList);
                                    //每次更新完數據，頁碼+1
                                    mRootView.setPageIndex(mRootView.getPageIndex() + 1);
                                } else {
                                    mRootView.getCurrentOrderFragment().showEmptyView(true, 0, null);
                                }
                            } else {
                                mRootView.getCurrentOrderFragment().showEmptyView(true, 0, null);
                            }
                        } else {
                            mRootView.getCurrentOrderFragment().showEmptyView(false, 0, null);
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.getCurrentOrderFragment().showEmptyView(false, 0, t);
                    }
                });
    }


    public boolean isNoMoreData() {
        return noMoreData;
    }

    public void setNoMoreData(boolean noMoreData) {
        this.noMoreData = noMoreData;
    }
}
