package com.gingersoft.supply_chain.mvp.presenter;

import android.app.Application;
import android.util.Log;

import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.utils.CollectionUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.supply_chain.mvp.bean.SupplierResultBean;
import com.gingersoft.supply_chain.mvp.bean.WareHouseListBean;
import com.gingersoft.supply_chain.mvp.content.Constant;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;

import javax.inject.Inject;

import com.gingersoft.supply_chain.mvp.contract.WareHouseListContract;
import com.jess.arms.utils.RxLifecycleUtils;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 01/06/2021 15:37
 * <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>
 * ================================================
 */
@FragmentScope
public class WareHouseListPresenter extends BasePresenter<WareHouseListContract.Model, WareHouseListContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    public final int SORT_UNIT_PRICE = 1;
    public final int SORT_WAREHOUSING_NUM = 2;
    public final int SORT_TOTAL_AMOUNT = 3;
    private WareHouseListBean.WareHousingDataBean data;

    @Inject
    public WareHouseListPresenter(WareHouseListContract.Model model, WareHouseListContract.View rootView) {
        super(model, rootView);
    }

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

    /**
     * 跟進類型排序
     *
     * @param type        類型
     * @param isAscending 升序或降序
     */
    public void sortByType(int type, boolean isAscending) {
        if (data == null || data.getPurchaseWarehousingOrderDetailsVOS() == null) {
            return;
        }
        if (type == SORT_UNIT_PRICE) {
            Collections.sort(data.getPurchaseWarehousingOrderDetailsVOS(), (o1, o2) -> {
                if (isAscending) {
                    return (int) (o1.getFoodPrice() - o2.getFoodPrice());
                } else {
                    return (int) (o2.getFoodPrice() - o1.getFoodPrice());
                }
            });
        } else if (type == SORT_WAREHOUSING_NUM) {
            //庫存數量
            Collections.sort(data.getPurchaseWarehousingOrderDetailsVOS(), (o1, o2) -> {
                if (isAscending) {
                    return o1.getFoodNum() - o2.getFoodNum();
                } else {
                    return o2.getFoodNum() - o1.getFoodNum();
                }
            });
        } else if (type == SORT_TOTAL_AMOUNT) {
            //總價
            Collections.sort(data.getPurchaseWarehousingOrderDetailsVOS(), (o1, o2) -> {
                if (isAscending) {
                    return (int) (o1.getFoodAmount() - o2.getFoodAmount());
                } else {
                    return (int) (o2.getFoodAmount() - o1.getFoodAmount());
                }
            });
        }
        mRootView.loadListInfo(data.getPurchaseWarehousingOrderDetailsVOS());
    }

    public void getWarehousing(int pageIndex, String foodName) {
        Map<String, Object> map = new HashMap<>(5);
        if (TextUtil.isNotEmptyOrNullOrUndefined(foodName)) {
            map.put("name", foodName);
        }
        Constant.addRestaurantId(map);
        Constant.addBrandId(map);
        Constant.addPageSize(map);
        map.put("pageIndex", pageIndex * Constant.PAGE_SIZE);
        mModel.getWarehousing(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(Constant.GET_INFO_LOADING))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<WareHouseListBean>(mErrorHandler) {
                    @Override
                    public void onNext(WareHouseListBean wareHouseListBean) {
                        if (wareHouseListBean.isSuccess()) {
                            mRootView.finishLoad();
                            if (data == null || pageIndex == 0) {
                                data = new WareHouseListBean.WareHousingDataBean();
                                data.setPurchaseWarehousingOrderDetailsVOS(new ArrayList<>());
                            }
                            data.setTotal(wareHouseListBean.getData().getTotal());
                            data.getPurchaseWarehousingOrderDetailsVOS().addAll(wareHouseListBean.getData().getPurchaseWarehousingOrderDetailsVOS());
                            mRootView.loadWarehousingInfo(data);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(wareHouseListBean.getErrMsg())) {
                            mRootView.showMessage(wareHouseListBean.getErrMsg());
                            mRootView.loadFail();
                        } else {
                            mRootView.showMessage(Constant.GET_INFO_ERROR);
                            mRootView.loadFail();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.loadFail();
                    }
                });
    }
}
