package com.gingersoft.gsa.delivery_pick_mode.mvp.presenter;

import android.app.Application;

import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.order.bean.mealManger.MyOrderManage;
import com.gingersoft.gsa.cloud.base.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.bean.RiceponAddOrderBean;
import com.gingersoft.gsa.cloud.print.bean.OrderDetails;
import com.gingersoft.gsa.delivery_pick_mode.mvp.contract.SendOrderContract;
import com.gingersoft.gsa.delivery_pick_mode.mvp.model.MemberAddressInfoBean;
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 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.FormBody;
import okhttp3.RequestBody;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 10/10/2020 14:40
 * <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>
 * ================================================
 */
@ActivityScope
public class SendOrderPresenter extends BasePresenter<SendOrderContract.Model, SendOrderContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;
    public List<OrderDetails.DataBean.PRODUCTNAMEBean> productnameBeans = new ArrayList<>();

    @Inject
    public SendOrderPresenter(SendOrderContract.Model model, SendOrderContract.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 getConfirmTakeawayOrderData() {
        Map<String, Object> map = new HashMap<>(6);
        map.put("memberId", 515);
        map.put("shopId", 26);
        map.put("price", 0);
        map.put("pageIndex", 1);
        map.put("isdefault", 1);
        map.put("pageSize", 15);
        mModel.getConfirmTakeawayOrderData(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> {
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<String>(mErrorHandler) {
                    @Override
                    public void onNext(String s) {
//                        https://hktest.ricepon.com:64377/member-web/api/member/getAddressAndResSetting?&pageSize=15&shopId=26&isdefault=1&pageIndex=1&price=0&memberId=515
                    }

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

    public void getMemberAddressInfo(String phone) {
        mModel.getMemberAddressInfo(phone)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("查詢會員信息..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<MemberAddressInfoBean>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull MemberAddressInfoBean info) {
                        if (info != null) {
                            if (info.isSuccess() && info.getData() != null) {
                                mRootView.loadMemberInfo(info.getData());
                            } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrorMsg())) {
                                mRootView.showMessage(info.getErrorMsg());
                            } else {
                                mRootView.showMessage("會員信息獲取失敗");
                            }
                        } else {
                            mRootView.showMessage("會員信息獲取失敗");
                        }
                    }
                });
    }

    public void submitOrder(String name, String phone, String address, String waimaiSendTime) {
        RequestBody requestBody = new FormBody.Builder()
                .add("order", getOrderJson(name, phone, address, waimaiSendTime))
                .add("apiversion", "1")
                .build();
        mModel.submitOrder(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("正在創建訂單..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<RiceponAddOrderBean>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull RiceponAddOrderBean info) {
                        if (info.getCode().equals("1")) {
                            mRootView.killMyself();
                        } else if(TextUtil.isNotEmptyOrNullOrUndefined(info.getErrorMsg())){
                            mRootView.showMessage(info.getErrorMsg());
                        }
                    }

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

    /**
     * 订单提交
     */
    private String getOrderJson(String name, String phone, String address, String waimaiSendTime) {
        JSONObject json;
        json = new JSONObject();
        try {
            json.put("shopId", GsaCloudApplication.getRestaurantId());
            json.put("phone", phone);
            json.put("transportationType", "0");//0  本店配送 ，是，1，Zeek，2，Lalamove
            json.put("memberId", GsaCloudApplication.getMemberId());
            json.put("addressDetail", address);
            json.put("orderRemark", "");
            json.put("payType", 5);
            //原价
            json.put("originalAmount", MyOrderManage.getInstance().getWholeAmount());
            json.put("orderType", 2);//訂單類型#1:餐廳訂單;2:線上外賣訂單3:扫码点餐;4固定二维码订单;5:预点餐;6:積分訂單;7:自取订单
            //实际总价
            json.put("totalPrice", MyOrderManage.getInstance().getTotalAmount());
            json.put("waimaiSendTime", waimaiSendTime);//送单时间
            JSONArray foodArray = new JSONArray();

            for (OrderDetails.DataBean.PRODUCTNAMEBean productnameBean : productnameBeans) {
                JSONObject food = getFoodJson(productnameBean);
                if (productnameBean.getChild() != null) {
                    JSONArray secondJsonArray = new JSONArray();
                    for (OrderDetails.DataBean.PRODUCTNAMEBean.ChildBeanX childBeanX : productnameBean.getChild()) {
                        JSONObject secondJsonObj = getFoodJson(childBeanX);
                        if (childBeanX.getChild() != null) {
                            JSONArray thirdJsonArray = new JSONArray();
                            for (OrderDetails.DataBean.PRODUCTNAMEBean.ChildBeanX.ChildBean childBean : childBeanX.getChild()) {
                                thirdJsonArray.put(getFoodJson(childBean));
                            }
                            secondJsonObj.put("itemDetail", thirdJsonArray);
                        }
                        secondJsonArray.put(secondJsonObj);
                        food.put("itemDetail", secondJsonArray);
                    }
                }
                foodArray.put(food);
            }
            json.put("foods", foodArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json.toString();
    }

    private JSONObject getFoodJson(OrderDetails.DataBean.PRODUCTNAMEBean.ChildBeanX.ChildBean childBean) {
        JSONObject object = new JSONObject();
        try {
            object.put("posFid", childBean.getPid());
            object.put("productId", childBean.getOdsId());
            object.put("productName", childBean.getPRODUCT_NAME());
            object.put("number", childBean.getNum());
            object.put("price", childBean.getPRICE());
            object.put("lunchboxPrice", childBean.getLunchboxPrice());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return object;
    }
    private JSONObject getFoodJson(OrderDetails.DataBean.PRODUCTNAMEBean.ChildBeanX childBean) {
        JSONObject object = new JSONObject();
        try {
            object.put("posFid", childBean.getPid());
            object.put("productId", childBean.getOdsId());
            object.put("productName", childBean.getPRODUCT_NAME());
            object.put("number", childBean.getNum());
            object.put("price", childBean.getPRICE());
            object.put("lunchboxPrice", childBean.getLunchboxPrice());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return object;
    }

    private JSONObject getFoodJson(OrderDetails.DataBean.PRODUCTNAMEBean productnameBean) {
        JSONObject object = new JSONObject();
        try {
            object.put("posFid", productnameBean.getPid());
            object.put("productId", productnameBean.getOdsId());
            object.put("productName", productnameBean.getPRODUCT_NAME());
            object.put("number", productnameBean.getNum());
            object.put("price", productnameBean.getPRICE());
            object.put("lunchboxPrice", productnameBean.getLunchboxPrice());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return object;
    }
}
