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

import android.app.Application;

import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.order.commodity.OrderDetail;
import com.gingersoft.gsa.cloud.order.contract.OrderStatusContract;
import com.gingersoft.gsa.cloud.table.mvp.contract.OrderCenterContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.response.OrderManagerResponse;
import com.gingersoft.gsa.cloud.table.mvp.model.utils.OrderAssemblyUtil;
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 BaseOrderConterPresenter<OrderCenterContract.Model, OrderCenterContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

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

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

    }

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

    /***
     * 獲取訂單列表
     * @param orderType
     * @param status
     * @param pageIndex
     * @param pageSize
     * @param refreshLayout
     * @param isLoadMore
     */
    public void loadOrderList(String orderType,String status, int pageIndex, int pageSize, RefreshLayout refreshLayout, boolean isLoadMore) {
        int restaurantId = RestaurantInfoManager.newInstance().getRestaurantId();
        if (pageIndex != 0) {
            //根據數據庫下標分頁
            pageIndex = pageIndex * pageSize;
        }
        mModel.loadOrderList(restaurantId, orderType,status, 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<OrderManagerResponse> orderItemList = JsonUtils.parseArray(result.getData(), OrderManagerResponse.class);
                                if (orderItemList != null && orderItemList.size() > 0) {
                                    if (!noMoreData) {
//                                        filterOrderItemsByStatus(orderItemList);
                                        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,String status) {
        int restaurantId = RestaurantInfoManager.newInstance().getRestaurantId();
        mModel.cancelOrder(orderId, restaurantId, orderType,status)
                .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<OrderManagerResponse> orderItemList = JsonUtils.parseArray(result.getData(), OrderManagerResponse.class);
                                if (orderItemList.size() > 0) {
//                                    filterOrderItemsByStatus(orderItemList);
                                    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;
    }
}
