package com.gingersoft.coldchain_module.mvp.presenter;

import android.app.Application;

import com.gingersoft.coldchain_module.mvp.constans.ColdChainConstants;
import com.gingersoft.coldchain_module.mvp.contract.SupplementOrderContract;
import com.gingersoft.coldchain_module.mvp.model.bean.SupplementInfoBean;
import com.gingersoft.coldchain_module.mvp.model.bean.SupplementResultBean;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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 SupplementOrderPresenter extends BasePresenter<SupplementOrderContract.Model, SupplementOrderContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public SupplementOrderPresenter(SupplementOrderContract.Model model, SupplementOrderContract.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) {
        //startTime  endTime
        RequestBody requestBody = new FormBody.Builder()
                .add("orderTypes", ColdChainConstants.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);
                        }
                    }
                });
    }

    public void submitOrder(int nowIndex, int allNum, String name, String phone, String address) {
        RequestBody requestBody = new FormBody.Builder()
                .add("order", getOrderJson(name, phone, address))
                .add("apiversion", "1")
                .build();
        mModel.submitOrder(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("剩餘" + nowIndex + "/" + allNum + "條訂單,,,"))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<SupplementResultBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull SupplementResultBean info) {
                        if (info != null) {
                            if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrorMsg())) {
                                mRootView.showMessage(info.getErrorMsg());
                            } else {
                                mRootView.showMessage("補單失敗");
                            }
                            if (info.getCode().equals("1")) {
                                mRootView.submissionComplete();
                            } else {
                                mRootView.killMyself();
                            }
                        } else {
                            mRootView.submissionFail();
                        }
                    }

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

    /**
     * 订单提交
     */
    private String getOrderJson(String name, String phone, String address) {
        JSONObject json;
        json = new JSONObject();
        try {
            json.put("shopId", GsaCloudApplication.getRestaurantId());
            json.put("phone", phone);
            json.put("replenishmentType", "1");
            json.put("transportationType", "3");
            json.put("memberId", GsaCloudApplication.getMemberId());
//            json.put("addressId", );
            json.put("addressDetail", address);
//            json.put("sendTime", );
            json.put("orderRemark", "");
            json.put("payType", 1);
            json.put("originalAmount", 0);//原价
            json.put("orderType", 8);
            json.put("totalPrice", 0);//实际总价
//            json.put("waimaiSendTime", waimaiSendTime);//送单时间

            JSONArray array = new JSONArray();

            JSONObject object = new JSONObject();
            object.put("posFid", -222);
            object.put("productId", -223);
            object.put("productName", "補單食品");
            object.put("number", 1);
            object.put("price", 0);
            object.put("lunchboxPrice", 0);

            array.put(object);

            json.put("foods", array);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json.toString();
    }

}
