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.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.base.order.bean.OrderDetail;
import com.gingersoft.gsa.cloud.base.order.bean.mealManger.MyOrderManage;
import com.gingersoft.gsa.cloud.base.utils.other.TextUtil;
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.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;

    @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) {
        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("正在創建訂單..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull BaseResult info) {

                    }

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

    /**
     * 订单提交
     */
    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("addressDetail", address);
            json.put("orderRemark", "");
            json.put("payType", 1);
            //原价
            json.put("originalAmount", MyOrderManage.getInstance().getWholeAmount());
            json.put("orderType", 8);
            //实际总价
            json.put("totalPrice", MyOrderManage.getInstance().getTotalAmount());
//            json.put("waimaiSendTime", waimaiSendTime);//送单时间
            JSONArray array = new JSONArray();

            List<OrderDetail> orderDetails = MyOrderManage.getInstance().getOrderFoodList();
            for (int i = 0; i < orderDetails.size(); i++) {
                OrderDetail orderDetail = orderDetails.get(i);
                JSONObject food = getFoodJson(orderDetail);
                if (i + 1 < orderDetails.size() && orderDetails.get(i + 1).getParentId() == orderDetail.getId()
                        && orderDetails.get(i + 1).getItemType() != 0) {
                    //如果下一個食品的父級id是當前食品的id
                    JSONArray foodArray = new JSONArray();
                    long foodId = orderDetail.getId();
                    for (int j = i + 1; j < orderDetails.size(); j++) {
                        OrderDetail secondOrderDetail = orderDetails.get(j);
                        JSONObject secondFood = getFoodJson(secondOrderDetail);
                        JSONArray secondArray = new JSONArray();
                        if (orderDetails.get(j).getParentId() == foodId) {
                            secondArray.put(secondFood);
                            long secondFoodId = secondOrderDetail.getId();
                            if (j + 1 < orderDetails.size() && orderDetails.get(j + 1).getParentId() == secondOrderDetail.getId()) {
                                for (int k = j + 1; k < orderDetails.size(); k++) {
                                    JSONObject thirdFood = getFoodJson(secondOrderDetail);
                                    JSONArray thirdArray = new JSONArray();
                                    if (orderDetails.get(k).getParentId() == secondFoodId) {
                                        thirdArray.put(getFoodJson(orderDetails.get(k)));
                                    } else {
                                        thirdFood.put("itemDetail", thirdArray);
                                        secondArray.put(thirdFood);
                                        i = k;
                                        break;
                                    }
                                }
                            }
                        } else {
                            secondFood.put("itemDetail", secondArray);
                            foodArray.put(secondFood);
                            i = j;
                            break;
                        }
                    }
                } else {
                    array.put(food);
                }
            }
            json.put("foods", array);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json.toString();
    }

    private JSONObject getFoodJson(OrderDetail orderDetail) {
        JSONObject object = new JSONObject();
        try {
            object.put("posFid", orderDetail.getParentId());
            object.put("productId", orderDetail.getId());
            object.put("productName", orderDetail.getProductName());
            object.put("number", orderDetail.getNumber());
            object.put("price", orderDetail.getPrice());
            object.put("lunchboxPrice", orderDetail.getLunchboxPrice());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return object;
    }

}
