package com.gingersoft.supply_chain.mvp.presenter;

import android.app.Application;

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.OrderBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseOrderDetailsBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseOrderResultBean;
import com.gingersoft.supply_chain.mvp.content.Constant;
import com.gingersoft.supply_chain.mvp.contract.PurchaseListContract;
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;

import static com.gingersoft.supply_chain.mvp.bean.PurchaseOrderDetailsBean.WAIT_RECEIVED;
import static com.gingersoft.supply_chain.mvp.content.Constant.PAGE_SIZE;


/**
 * Description:採購列表
 */
@FragmentScope
public class PurchaseListPresenter extends BasePresenter<PurchaseListContract.Model, PurchaseListContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public PurchaseListPresenter(PurchaseListContract.Model model, PurchaseListContract.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 getOrderList(String orderNo, int orderStatus, int pageIndex) {
        Map<String, Object> map = new HashMap<>(6);
        Constant.addRestaurantId(map);
        Constant.addBrandId(map);
        Constant.addPageSize(map);
        if (TextUtil.isNotEmptyOrNullOrUndefined(orderNo)) {
            map.put("orderNo", orderNo);
        }
        if (orderStatus != 0) {
            if (orderStatus == PurchaseOrderDetailsBean.WAIT_RECEIVED) {
                //如果是查未完成訂單，需要傳入兩個狀態，未收貨和部分收貨
                List<Integer> list = new ArrayList<>();
                list.add(PurchaseOrderDetailsBean.WAIT_RECEIVED);
                list.add(PurchaseOrderDetailsBean.PART_RECEIVED);
                map.put("status", "1,2");
            } else {
                map.put("status", orderStatus);
            }
        }
        map.put("pageIndex", pageIndex * PAGE_SIZE);
        mModel.getOrderList(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<PurchaseOrderResultBean>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull PurchaseOrderResultBean info) {
                        if (info.isSuccess()) {
                            mRootView.loadOrderList(info.getData().getList());
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                            mRootView.showMessage(info.getErrMsg());
                            mRootView.loadFail();
                        } else {
                            mRootView.loadFail();
                        }
                    }

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

    /**
     * 刪除訂單
     *
     * @param position 訂單下標
     * @param orderId  訂單id
     */
    public void deleteOrder(int position, int orderId) {
        mModel.deleteOrder(orderId)
                .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.isSuccess()) {
                            mRootView.deleteOrder(position);
                        }
                    }
                });
    }
}
