package com.gingersoft.supply_chain.mvp.presenter;

import android.app.Application;

import com.chad.library.adapter.base.BaseBinderAdapter;
import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.constans.AppConstant;
import com.gingersoft.gsa.cloud.common.utils.CollectionUtils;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.mvp.bean.SnInOutBoundRecordDetailsBean;
import com.gingersoft.supply_chain.mvp.bean.SnInoutBoundRecordBean;
import com.gingersoft.supply_chain.mvp.content.PurchaseConstant;
import com.gingersoft.supply_chain.mvp.ui.adapter.binder.SnInOutRecordBinder;
import com.gingersoft.supply_chain.mvp.ui.adapter.binder.SnInRecordDetailsBinder;
import com.gingersoft.supply_chain.mvp.ui.adapter.binder.SnOutRecordDetailsBinder;
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.SnInOutboundRecordsContract;
import com.jess.arms.utils.RxLifecycleUtils;

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


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 05/11/2021 11:05
 * <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 SnInOutboundRecordsPresenter extends BasePresenter<SnInOutboundRecordsContract.Model, SnInOutboundRecordsContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    private BaseBinderAdapter baseBinderAdapter;

    @Inject
    public SnInOutboundRecordsPresenter(SnInOutboundRecordsContract.Model model, SnInOutboundRecordsContract.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 getFoodInOutBoundRecordBySnCode(String encodeSnNo) {
        if (TextUtil.isEmptyOrNullOrUndefined(encodeSnNo)) {
            mRootView.showMessage(mApplication.getString(R.string.str_please_input_sn));
            return;
        }
        Map<String, Object> map = new HashMap<>(3);
        AppConstant.addRestaurantId(map);
        AppConstant.addBrandId(map);
        map.put("encodeSnNo", encodeSnNo);
        mModel.getFoodInOutBoundRecordBySnCode(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(AppConstant.GET_INFO_LOADING))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResult result) {
                        if (result != null && result.isSuccess() && result.getData() != null) {
                            List<SnInoutBoundRecordBean> snInoutBoundRecordBeans = GsonUtils.jsonToList(result.getData(), SnInoutBoundRecordBean.class);
                            if (CollectionUtils.isNullOrEmpty(snInoutBoundRecordBeans)) {
                                mRootView.showMessage(mApplication.getString(R.string.str_no_data_found));
                                mRootView.showEmpty();
                            } else {
                                loadAdapter(snInoutBoundRecordBeans);
                            }
                        } else {
                            showErrMsg(result);
                        }
                    }

                    private void loadAdapter(List<SnInoutBoundRecordBean> snInoutBoundRecordBeans) {
                        if (baseBinderAdapter == null) {
                            baseBinderAdapter = new BaseBinderAdapter();
                            baseBinderAdapter.addItemBinder(SnInoutBoundRecordBean.class, new SnInOutRecordBinder())
                                    .addItemBinder(SnInOutBoundRecordDetailsBean.ConsumeDetailsBean.class, new SnOutRecordDetailsBinder())
                                    .addItemBinder(SnInOutBoundRecordDetailsBean.InventoryDetailsBean.class, new SnInRecordDetailsBinder());
                            baseBinderAdapter.addData(snInoutBoundRecordBeans);
                            mRootView.loadAdapter(baseBinderAdapter);
                            baseBinderAdapter.setOnItemClickListener((adapter, view, position) -> {
                                Object item = baseBinderAdapter.getItem(position);
                                if (item instanceof SnInoutBoundRecordBean) {
                                    SnInoutBoundRecordBean recordBean = (SnInoutBoundRecordBean) item;
                                    if (!recordBean.isLoadDetails()) {
                                        getFoodInOutBoundDetails(recordBean.getPurchaseWarehousingOrderDetailsIds(), recordBean.getEncodeSnNo(), recordBean.getEncodeFoodNo());
                                        recordBean.setLoadDetails(true);
                                    }
                                }
                            });
                        } else {
                            baseBinderAdapter.setList(snInoutBoundRecordBeans);
                        }
                    }
                });
    }

    private void showErrMsg(BaseResult result) {
        if (result != null && TextUtil.isNotEmptyOrNullOrUndefined(result.getErrMsg())) {
            mRootView.showMessage(result.getErrMsg());
        } else {
            mRootView.showMessage(AppConstant.GET_INFO_ERROR);
        }
        mRootView.showEmpty();
    }

    public void getFoodInOutBoundDetails(String purchaseWarehousingOrderDetailsIds, String encodeSnNo, String encodeFoodNo) {
        Map<String, Object> map = new HashMap<>(5);
        map.put("purchaseWarehousingOrderDetailsIds", purchaseWarehousingOrderDetailsIds);
        AppConstant.addRestaurantId(map);
        AppConstant.addBrandId(map);
        map.put("encodeSnNo", encodeSnNo);
        map.put("encodeFoodNo", encodeFoodNo);
        mModel.getFoodInOutBoundRecordDetails(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(AppConstant.GET_INFO_LOADING))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResult result) {
                        if (result != null && result.isSuccess() && result.getData() != null) {
                            SnInOutBoundRecordDetailsBean detailsBean = GsonUtils.GsonToBean(result.getData(), SnInOutBoundRecordDetailsBean.class);
                            baseBinderAdapter.addData(detailsBean.getConsumeDetails());
                            baseBinderAdapter.addData(detailsBean.getInventoryDetails());
                        } else {
                            showErrMsg(result);
                        }
                    }
                });
    }
}
