package com.gingersoft.supply_chain.mvp.presenter;

import android.app.Application;

import com.gingersoft.gsa.cloud.common.core.restaurant.ResturantInfoManager;
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.SupplierInfoBean;
import com.gingersoft.supply_chain.mvp.bean.SupplierResultBean;
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 java.util.ArrayList;
import java.util.HashMap;
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;
    @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 getSupplierList(String content, int pageIndex) {
        Map<String, Object> map = new HashMap<>();
        map.put("pageSize", 10);
        map.put("pageIndex", pageIndex);
        map.put("restaurantId", ResturantInfoManager.newInstance().getRestaurantId());
        map.put("brandId", ResturantInfoManager.newInstance().getBrandId());
        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();
                                }
                                supplierBeanList.addAll(info.getData().getList());
                                mRootView.loadSupplierList(supplierBeanList);
                            } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.loadError();
                            }
                        }
                    }

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

    public void deleteSupplier(SupplierInfoBean supplierBean, int position) {
        supplierBean.setDeletes(1);
        supplierBean.setSupplierNo(null);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(supplierBean));
        mModel.updateSupplier(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("刪除中..."))
                .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()) {
                                mRootView.deleteSuccess(position);
                            } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            } else {
                                mRootView.showMessage("保存失敗");
                            }
                        }
                    }
                });
    }

}
