package com.gingersoft.supply_chain.mvp.presenter;

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.gson.GsonUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;
import com.gingersoft.supply_chain.mvp.bean.SupplierInfoBean;
import com.gingersoft.supply_chain.mvp.bean.SupplierResultBean;
import com.gingersoft.supply_chain.mvp.content.Constant;
import com.gingersoft.supply_chain.mvp.content.SupplyShoppingCart;
import com.gingersoft.supply_chain.mvp.contract.SupplierListContract;
import com.jess.arms.di.scope.FragmentScope;
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.xuexiang.rxutil2.rxjava.RxJavaUtils;
import com.xuexiang.rxutil2.rxjava.task.RxAsyncTask;
import com.xuexiang.rxutil2.rxjava.task.RxIOTask;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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.MediaType;
import okhttp3.RequestBody;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 11/19/2020 17:41
 * <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 SupplierListPresenter extends BasePresenter<SupplierListContract.Model, SupplierListContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private List<SupplierInfoBean> supplierBeanList;
    private String supplierName;

    @Inject
    public SupplierListPresenter(SupplierListContract.Model model, SupplierListContract.View rootView) {
        super(model, rootView);
    }

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

    public void setSupplierName(String supplierName) {
        this.supplierName = supplierName;
    }

    /**
     * 獲取供應商列表
     *
     * @param content      用於搜索的內容
     * @param pageIndex    頁數
     * @param needGetIndex 是否需要遍歷來獲取默認選中的供應商
     */
    public void getSupplierList(String content, int pageIndex, boolean needGetIndex) {
        Map<String, Object> map = new HashMap<>(5);
        map.put("pageSize", Constant.PAGE_SIZE);
        map.put("pageIndex", pageIndex * Constant.PAGE_SIZE);
        Constant.addRestaurantId(map);
        Constant.addBrandId(map);
        if (!TextUtil.isEmptyOrNullOrUndefined(content)) {
            map.put("content", content);
        }
        mModel.getSupplierList(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("獲取中..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<SupplierResultBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull SupplierResultBean info) {
                        if (info != null) {
                            if (info.isSuccess()) {
                                if (supplierBeanList == null) {
                                    supplierBeanList = new ArrayList<>();
                                }
                                if (pageIndex == 0) {
                                    supplierBeanList.clear();
                                }
                                if (info.getData() != null) {
                                    List<SupplierInfoBean> list = info.getData().getList();
                                    supplierBeanList.addAll(list);
                                }
                                mRootView.loadSupplierList(supplierBeanList);

                                if (info.getData() != null) {
                                    if (needGetIndex && TextUtil.isNotEmptyOrNullOrUndefined(supplierName)) {
                                        //當前頁面用於選擇，並且供應商名稱不為空，遍歷獲取默認選中的供應商
                                        RxJavaUtils.executeAsyncTask(new RxAsyncTask<Object, Integer>(1) {
                                            @Override
                                            public void doInUIThread(Integer o) {
                                                if (o != null) {
                                                    mRootView.setSelectIndex(o);
                                                }
                                            }

                                            @Override
                                            public Integer doInIOThread(Object o) {
                                                List<SupplierInfoBean> list = info.getData().getList();
                                                if (list != null) {
                                                    int size = list.size();
                                                    for (int i = 0; i < size; i++) {
                                                        if (list.get(i).getSupplierName().equals(supplierName)) {
                                                            return supplierBeanList.size() - list.size() + i;
                                                        }
                                                    }
                                                }
                                                return null;
                                            }
                                        });
                                    }
                                }
                            } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.loadError();
                            }
                        }
                    }

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

    /**
     * 刪除供應商
     *
     * @param id       供應商id
     * @param position 所刪除的供應商下標
     */
    public void deleteSupplier(int id, int position) {
        mModel.deleteSupplier(id)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(Constant.DELETE_LOADING))
                .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) {
                            if (info.isSuccess()) {
                                SupplyShoppingCart.getInstance().removeFoodsBySupplier(id);
                                mRootView.deleteSuccess(position);
                            } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.showMessage(Constant.DELETE_FAIL);
                            }
                        }
                    }
                });
    }

}
