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.constans.AppConstant;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.common.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.supply_chain.mvp.bean.DishDetailBean;
import com.gingersoft.supply_chain.mvp.bean.DishDetailResultBean;
import com.gingersoft.supply_chain.mvp.bean.DishesResultBean;
import com.gingersoft.supply_chain.mvp.contract.DishesContract;
import com.gingersoft.supply_chain.mvp.ui.adapter.dishes.DishNode;
import com.gingersoft.supply_chain.mvp.ui.adapter.dishes.DishesGroupNode;
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 org.jetbrains.annotations.NotNull;

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.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * ================================================
 * 菜品
 * ================================================
 */
@FragmentScope
public class DishesPresenter extends BasePresenter<DishesContract.Model, DishesContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;


    @Inject
    public DishesPresenter(DishesContract.Model model, DishesContract.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 getDishGroupData() {
        Map<String, Object> map = new HashMap<>(2);
        AppConstant.addBrandId(map);
        AppConstant.addRestaurantId(map);
        mModel.getDishGroupData(map)//發送請求
                .subscribeOn(Schedulers.io())//切換到io異步線程
                .doOnSubscribe(disposable -> mRootView.showLoading(AppConstant.GET_INFO_LOADING))//顯示加載提示框
                .subscribeOn(AndroidSchedulers.mainThread())//切換到主線程，上面的提示框就在主線程
                .observeOn(AndroidSchedulers.mainThread())//切換到主線程，隱藏提示框在主線程
                .doAfterTerminate(() -> mRootView.hideLoading())//任務執行完成後，隱藏提示框
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//綁定生命週期，頁面隱藏時斷開請求
                .observeOn(AndroidSchedulers.mainThread())//切換到主線程
                .subscribe(new ErrorHandleSubscriber<DishesResultBean>(mErrorHandler) {//mErrorHandler是統一的錯誤處理
                    @Override
                    public void onNext(DishesResultBean dishGroup) {//數據處理
                        if (dishGroup.isSuccess()) {
                            List<DishesGroupNode> data = dishGroup.getData();
                            mRootView.loadDishGroupInfo(data);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(dishGroup.getErrMsg())) {
                            mRootView.showMessage(dishGroup.getErrMsg());
                            mRootView.loadDishGroupFail();
                        } else {
                            mRootView.showMessage(AppConstant.GET_INFO_ERROR);
                            mRootView.loadDishGroupFail();
                        }
                    }

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


    public void getDishesDetailData(final DishNode dishNode) {
        Map<String, Object> map = new HashMap<>(4);
        map.put("biFoodId",String.valueOf(dishNode.getId()));
        map.put("type","0");
        AppConstant.addBrandId(map);
        AppConstant.addRestaurantId(map);
        mModel.getDishesDetailData(map)//發送請求
                .subscribeOn(Schedulers.io())//切換到io異步線程
                .doOnSubscribe(disposable -> mRootView.showLoading(AppConstant.GET_INFO_LOADING))//顯示加載提示框
                .subscribeOn(AndroidSchedulers.mainThread())//切換到主線程，上面的提示框就在主線程
                .observeOn(AndroidSchedulers.mainThread())//切換到主線程，隱藏提示框在主線程
                .doAfterTerminate(() -> mRootView.hideLoading())//任務執行完成後，隱藏提示框
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//綁定生命週期，頁面隱藏時斷開請求
                .observeOn(AndroidSchedulers.mainThread())//切換到主線程
                .subscribe(new ErrorHandleSubscriber<DishDetailResultBean>(mErrorHandler) {//mErrorHandler是統一的錯誤處理
                    @Override
                    public void onNext(DishDetailResultBean dishDetailBean) {//數據處理
                        if (dishDetailBean.isSuccess()) {
                            dishNode.setDetailBean(dishDetailBean);
                            mRootView.loadDishesInfo(dishNode,dishDetailBean);
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(dishDetailBean.getErrMsg())) {
                            mRootView.showMessage(dishDetailBean.getErrMsg());
                            mRootView.loadDishesFail();
                        } else {
                            mRootView.loadDishesFail();
                            mRootView.showMessage(AppConstant.GET_INFO_ERROR);
                        }
                    }

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


    public void bindDishFoods( final DishNode dishNode,List<DishDetailBean> dishDetailBeans ) {
        mModel.bindDishes(RequestBody.create(MediaType.parse("application/json"), JsonUtils.toJson(dishDetailBeans)))//發送請求
                .subscribeOn(Schedulers.io())//切換到io異步線程
                .doOnSubscribe(disposable -> mRootView.showLoading(AppConstant.GET_INFO_LOADING))//顯示加載提示框
                .subscribeOn(AndroidSchedulers.mainThread())//切換到主線程，上面的提示框就在主線程
                .observeOn(AndroidSchedulers.mainThread())//切換到主線程，隱藏提示框在主線程
                .doAfterTerminate(() -> mRootView.hideLoading())//任務執行完成後，隱藏提示框
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//綁定生命週期，頁面隱藏時斷開請求
                .observeOn(AndroidSchedulers.mainThread())//切換到主線程
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {//mErrorHandler是統一的錯誤處理
                    @Override
                    public void onNext(BaseResult bindResult) {//數據處理
                        if (bindResult.isSuccess()) {
                            DishDetailResultBean dishDetailResultBean=new DishDetailResultBean();
                            dishDetailResultBean.setData(dishDetailBeans);
                            dishNode.setDetailBean(dishDetailResultBean);
                            mRootView.showMessage("菜品食材綁定成功");
                            mRootView.bindDishFoods(dishNode);

                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(bindResult.getErrMsg())) {
                            mRootView.showMessage(bindResult.getErrMsg());
                        } else {
                            mRootView.showMessage(AppConstant.GET_INFO_ERROR);
                        }
                    }
                });
    }
}