package com.gingersoft.gsa.cloud.main.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.gsa.cloud.main.mvp.contract.NewlyAddedContract;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.SummaryBean;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.TimePeriodBean;
import com.gingersoft.gsa.cloud.main.mvp.ui.adapter.foodmenu.FoodMenuAdapter;
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 javax.inject.Inject;

import io.reactivex.Observable;
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;

import static com.gingersoft.gsa.cloud.main.mvp.ui.fragment.menu.BaseFoodMenuFragment.NEW_FOOD_TYPE;
import static com.gingersoft.gsa.cloud.main.mvp.ui.fragment.menu.BaseFoodMenuFragment.NEW_TIME_PERIOD;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 11/03/2020 09:53
 * <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 NewlyAddedPresenter extends BasePresenter<NewlyAddedContract.Model, NewlyAddedContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public NewlyAddedPresenter(NewlyAddedContract.Model model, NewlyAddedContract.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 saveInfoByType(int fragmentType, FoodMenuAdapter foodMenuAdapter, boolean isUpdate) {
        if (fragmentType == NEW_TIME_PERIOD) {
            //新增時段
            addTimePeriod(foodMenuAdapter.getTimePeriodInfo(), isUpdate);
        } else if(fragmentType == NEW_FOOD_TYPE){
            addSummary(foodMenuAdapter.getSummaryInfo(), isUpdate);
        }
    }

    /**
     * 餐種
     *
     * @param summaryBean 餐種數據
     */
    private void addSummary(SummaryBean summaryBean, boolean isUpdate) {
        if (TextUtil.isEmptyOrNullOrUndefined(summaryBean.getName())) {
            mRootView.showMessage("請輸入餐種名稱");
            return;
        }
        Observable<BaseResult> baseResultObservable;
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(summaryBean));
        if (isUpdate) {
            baseResultObservable = mModel.updateSummary(requestBody);
        } else {
            baseResultObservable = mModel.addSummary(requestBody);
        }
        baseResultObservable.subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .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.isSuccess()) {
                            mRootView.showMessage("保存成功");
                            mRootView.killMyself();
                        }
                    }
                });
    }

    /**
     * 時段
     *
     * @param timePeriodBean 時段數據
     */
    private void addTimePeriod(TimePeriodBean timePeriodBean, boolean isUpdate) {
        if (TextUtil.isEmptyOrNullOrUndefined(timePeriodBean.getPeriodName1())) {
            mRootView.showMessage("請輸入時段名稱");
            return;
        }
        Observable<BaseResult> baseResultObservable;
        timePeriodBean.setBrandId(ResturantInfoManager.newInstance().getBrandId());
        timePeriodBean.setRestaurantId(ResturantInfoManager.newInstance().getRestaurantId());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(timePeriodBean));
        if (isUpdate) {
            baseResultObservable = mModel.updatePeriod(requestBody);
        } else {
            baseResultObservable = mModel.addPeriod(requestBody);
        }
        baseResultObservable.subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .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.isSuccess()) {
                            mRootView.showMessage("保存成功");
                            mRootView.killMyself();
                        }
                    }
                });
    }


}
