package com.gingersoft.coldchain_module.mvp.presenter;

import android.app.Application;

import com.gingersoft.coldchain_module.mvp.constans.ColdChainConstans;
import com.gingersoft.coldchain_module.mvp.contract.ColdChainMainContract;
import com.gingersoft.coldchain_module.mvp.model.bean.BalanceBean;
import com.gingersoft.coldchain_module.mvp.model.bean.PickUpBean;
import com.gingersoft.coldchain_module.mvp.model.bean.SupplementInfoBean;
import com.gingersoft.coldchain_module.mvp.model.bean.UpdateRestaurantStateBean;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.other.TextUtil;
import com.jess.arms.di.scope.ActivityScope;
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.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

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


@ActivityScope
public class ColdChainMainPresenter extends BasePresenter<ColdChainMainContract.Model, ColdChainMainContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public ColdChainMainPresenter(ColdChainMainContract.Model model, ColdChainMainContract.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 getNumByOrderType(int restaurantId, Method method, Object object) {
        //startTime  endTime
        RequestBody requestBody = new FormBody.Builder()
                .add("orderTypes", ColdChainConstans.orderType + "")
                .add("restaurantId", restaurantId + "")
                .build();
        mModel.getNumByOrderType(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("獲取餐廳配置信息..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<SupplementInfoBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull SupplementInfoBean info) {
                        if (info != null && info.isSuccess()) {
//                            mRootView.loadNumber(info);
                            try {
                                method.setAccessible(true);
                                method.invoke(object, info);
                            } catch (IllegalAccessException | InvocationTargetException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }


    public void pickUp(int restaurantId) {
        //startTime  endTime
        RequestBody requestBody = new FormBody.Builder()
                .add("orderType", ColdChainConstans.orderType + "")
                .add("restaurantId", restaurantId + "")
                .build();
        mModel.pickUp(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("提交訂單中..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<PickUpBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull PickUpBean info) {
                        if (info != null) {
                            if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrorMsg())) {
                                mRootView.showMessage(info.getErrorMsg());
                            } else {
                                mRootView.showMessage(info.isSuccess() ? "提交成功" : "提交失敗");
                            }
                        }
                    }
                });
    }

    public void getBalance() {
        mModel.getBalance(GsaCloudApplication.getBrandId() + "")
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> {
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BalanceBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BalanceBean info) {
                        if (info != null && info.isSuccess() && info.getData() != null) {
                            mRootView.loadBalance(info.getData().getBalance(), info.getData().getBond(), info.getData().getBalance() <= info.getData().getThreshold());
                        }
                    }
                });
    }

    public void updateRestOpenStatus(int state, int restaurantId) {
        RequestBody requestBody = new FormBody.Builder()
                .add("openStatus", state + "")
                .add("restId", restaurantId + "")
                .build();
        mModel.updateRestOpenStatus(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("修改狀態中..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<UpdateRestaurantStateBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull UpdateRestaurantStateBean info) {
                        if (info != null && info.isSuccess()) {
                            mRootView.setRestaurantState(state);
                        } else if(info != null && info.getData() != null && TextUtil.isNotEmptyOrNullOrUndefined(info.getData().getMsg())){
                            mRootView.showMessage(info.getData().getMsg());
                        } else {
                            mRootView.showMessage("修改狀態失敗");
                        }
                    }
                });
    }
}
