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

import android.app.Activity;
import android.app.Application;

import com.gingersoft.gsa.cloud.account.restaurant.ResturantInfoManager;
import com.gingersoft.gsa.cloud.account.user.UserContext;

import com.gingersoft.gsa.cloud.base.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.base.order.order.TakeawayOrder;
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.data.model.bean.UpdateOrderStatusBean;
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.List;
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<>();
    public List<MemberAddressInfoBean.DataBean> addressData;
    public String addressId;

    @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 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().get(0));
                                addressData = 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")) {
                            gsUpdateOrderStatus(info.getOrderId() + "");
                        } else if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrorMsg())) {
                            mRootView.showMessage(info.getErrorMsg());
                        } else {
                            mRootView.showMessage("創建訂單失敗");
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.showMessage("創建訂單失敗" + t.getMessage());
                    }
                });
    }

    private void gsUpdateOrderStatus(String orderId) {
        RequestBody requestBody = new FormBody.Builder()
                .add("orderId", orderId)
                .add("status", "2")
                .add("orderType", "2")//訂單類型#1:餐廳訂單;2:線上外賣訂單3:扫码点餐;4固定二维码订单;5:预点餐;6:積分訂單;7:自取订单'
                .add("type", "2")//通知類型：1.未定，2:外賣
                .add("confirmationType", "1")//接單類型，1 手動接單  2，自動接單
                .add("orderFrom", "2")//订单来源#1:ios;2:安卓;3:gspos;4:web;5:第三方POS A;6:第三方POS B;
                .build();
        mModel.gsUpdateOrderStatus(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("確認訂單中..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> {})
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<UpdateOrderStatusBean>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull UpdateOrderStatusBean info) {
                        //添加PRJ
                        addPrj(orderId);
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        kill();
                        mRootView.showMessage("修改訂單狀態失敗" + t.getMessage());
                    }
                });
    }

    public void addPrj(String orderId) {
        StringBuilder ids = new StringBuilder();
        for (OrderDetails.DataBean.PRODUCTNAMEBean productnameBean : productnameBeans) {
            if (productnameBean.getChild() != null) {
                for (OrderDetails.DataBean.PRODUCTNAMEBean.ChildBeanX childBeanX : productnameBean.getChild()) {
                    if (childBeanX.getChild() != null) {
                        for (OrderDetails.DataBean.PRODUCTNAMEBean.ChildBeanX.ChildBean childBean : childBeanX.getChild()) {
                            ids.append(childBean.getOdsId());
                            ids.append(",");
                        }
                    }
                    ids.append(childBeanX.getOdsId());
                    ids.append(",");
                }
            }
            ids.append(productnameBean.getOdsId());
            ids.append(",");
        }
        RequestBody requestBody = new FormBody.Builder()
                .add("orderId", orderId)
                .add("restaurantId", ResturantInfoManager.newInstance().getRestaurantId() + "")
                .add("orderDetailsIds", ids.toString())
                .build();
        mModel.addPrj(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("添加廚房打印數據..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> {})
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResult s) {
                        TakeawayOrder.getInstance().initialization();
                        kill();
                    }
                });
    }

    private void kill() {
        List<Activity> activities = mAppManager.getActivityList();
        for (Activity activity : activities) {
            Class<? extends Activity> aClass = activity.getClass();
            if (aClass.getName().equals("com.gingersoft.gsa.cloud.table.mvp.ui.activity.MealStandActivity") || aClass.getName().equals("com.gingersoft.gsa.cloud.table.mvp.ui.activity.OrderContentActivity")) {
                activity.finish();
            }
        }
        TakeawayOrder.getInstance().getShoppingCart().initialization(true);
        mRootView.killMyself();
    }

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

            JSONArray foodArray = new JSONArray();
            for (OrderDetails.DataBean.PRODUCTNAMEBean productnameBean : productnameBeans) {
                JSONObject food = getFoodJson(productnameBean);
                JSONArray itemArray = new JSONArray();

                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);
                        itemArray.put(secondJsonArray);
                        food.put("itemDetail", itemArray);
                    }
                }
                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;
    }
}
