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.ColdChainMainContract;
import com.gingersoft.coldchain_module.mvp.model.bean.BalanceBean;
import com.gingersoft.coldchain_module.mvp.model.bean.OrderList;
import com.gingersoft.coldchain_module.mvp.model.bean.PickUpBean;
import com.gingersoft.coldchain_module.mvp.model.bean.ShipAnyOrdersNewBean;
import com.gingersoft.coldchain_module.mvp.model.bean.SupplementInfoBean;
import com.gingersoft.coldchain_module.mvp.model.bean.ThirdItem;
import com.gingersoft.coldchain_module.mvp.model.bean.UpdateOrderStatusBean;
import com.gingersoft.coldchain_module.mvp.model.bean.UpdateRestaurantStateBean;
import com.gingersoft.gsa.cloud.app.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.RestaurantExpandInfoUtils;
import com.gingersoft.gsa.cloud.base.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.base.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.print.bean.OrderDetails;
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 java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
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.disposables.Disposable;
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 ColdChainMainPresenter extends BasePresenter<ColdChainMainContract.Model, ColdChainMainContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public ColdChainMainPresenter(ColdChainMainContract.Model model, ColdChainMainContract.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, Method method, Object object) {
        //startTime  endTime
        RequestBody requestBody = new FormBody.Builder()
                .add("orderTypes", ColdChainConstants.orderType + "")
                .add("restaurantId", restaurantId + "")
                .build();
        mModel.getNumByOrderType(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> {
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<SupplementInfoBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull SupplementInfoBean info) {
                        if (info != null && info.isSuccess()) {
                            //                            mRootView.loadNumber(info);
//                            try {
                                method.setAccessible(true);
                            try {
                                method.invoke(object, info);
                            } catch (IllegalAccessException | InvocationTargetException e) {
                                e.printStackTrace();
                            }
//                            } catch (IllegalAccessException | InvocationTargetException e) {
//                                e.printStackTrace();
//                            }
                        }
                    }
                });
    }


    public void pickUp(int restaurantId) {
        //startTime  endTime
        RequestBody requestBody = new FormBody.Builder()
                .add("orderType", ColdChainConstants.orderType + "")
                .add("restaurantId", restaurantId + "")
                .build();
        mModel.pickUp(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("提交訂單中..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<PickUpBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull PickUpBean info) {
                        if (info != null) {
                            if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrorMsg())) {
                                mRootView.showMessage(info.getErrorMsg());
                            } else {
                                mRootView.showMessage(info.isSuccess() ? "提交成功" : "提交失敗");
                            }
                        }
                    }
                });
    }

    public void getBalance() {
        mModel.getBalance(GsaCloudApplication.getBrandId() + "")
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> {
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BalanceBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BalanceBean info) {
                        if (info != null && info.isSuccess() && info.getData() != null) {
                            mRootView.loadBalance(info.getData().getBalance(), info.getData().getBond(), info.getData().getBalance() <= info.getData().getThreshold());
                        }
                    }
                });
    }

    public void updateRestOpenStatus(int state, int restaurantId) {
        RequestBody requestBody = new FormBody.Builder()
                .add("openStatus", state + "")
                .add("restId", restaurantId + "")
                .build();
        mModel.updateRestOpenStatus(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("修改狀態中..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<UpdateRestaurantStateBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull UpdateRestaurantStateBean info) {
                        if (info != null && info.isSuccess()) {
                            mRootView.setRestaurantState(state);
                        } else if (info != null && info.getData() != null && TextUtil.isNotEmptyOrNullOrUndefined(info.getData().getMsg())) {
                            mRootView.showMessage(info.getData().getMsg());
                        } else {
                            mRootView.showMessage("修改狀態失敗");
                        }
                    }
                });
    }

    public void updateExpandInfo(String settingName, String[] valueType, String[] value) {
        FormBody.Builder builder = new FormBody.Builder()
                .add("id", RestaurantExpandInfoUtils.getId(settingName) + "")
                .add("restaurantId", GsaCloudApplication.getRestaurantId() + "")
                .add("settingName", settingName);
        for (int i = 0; i < valueType.length; i++) {
            builder.add(valueType[i], value[i]);
        }
        mModel.updateRestOpenStatus(builder.build())
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> {
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<UpdateRestaurantStateBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull UpdateRestaurantStateBean info) {

                    }

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

    private List<Integer> ids;
    private Disposable autoDisposable;
    private boolean isAutoReceiving;

    public void stopAutoReceivingOrders() {
        if (autoDisposable != null) {
            autoDisposable.dispose();
        }
        errorCount = 6;
        isAutoReceiving = false;
    }

    /**
     * 獲取待確認訂單(開了自動接單調用此方法接單)
     *
     * @param restaurantId
     */
    public void startToBeConfirmedOrderList(int restaurantId) {
        if (autoDisposable != null && (!autoDisposable.isDisposed() || !isAutoReceiving)) {
            return;
        }
        isAutoReceiving = true;
        errorCount = 0;
        RequestBody requestBody = new FormBody.Builder()
                .add("restaurantId", restaurantId + "")
                .add("page", "0")
                .add("pageSize", "")
                .add("status", "0,1")
                .add("type", ColdChainConstants.orderType + "")
                .build();
        mModel.getOrderList(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> {
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<OrderList>(mErrorHandler) {

                    @Override
                    public void onSubscribe(Disposable d) {
                        super.onSubscribe(d);
                        autoDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull OrderList info) {
                        if (info != null && info.isSuccess() && info.getData() != null) {
                            if (info.getData().getData() != null && info.getData().getData().size() > 0) {
                                List<OrderList.DataBeanX.DataBean> dataBeans = info.getData().getData();
                                dataBeans.remove(dataBeans.size() - 1);

                                ids = new ArrayList<>();
                                for (int i = 0; i < dataBeans.size(); i++) {
                                    ids.add(dataBeans.get(i).getId());
                                }
                                if (ids.size() > 0) {
                                    findOrderDetails(ids.get(0));
                                    ids.remove(0);
                                }
                            }
                        }
                    }
                });
    }

    public void findOrderDetails(int orderId) {
        if (!isAutoReceiving) {
            return;
        }
        //startTime  endTime  //mRootView.showLoading("獲取訂單詳情...")  mRootView.hideLoading()
        RequestBody requestBody = new FormBody.Builder()
                .add("orderId", orderId + "")
                .build();
        mModel.findOrderDetails(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> {
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<OrderDetails>(mErrorHandler) {
                    @Override
                    public void onSubscribe(Disposable d) {
                        super.onSubscribe(d);
                        autoDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull OrderDetails info) {
                        if (info != null && info.getData() != null && info.getData().size() > 0) {
                            thirdDelivery(info.getData().get(0));
                        } else {
                            if (errorCount < 5) {
                                startToBeConfirmedOrderList(GsaCloudApplication.getRestaurantId());
                                errorCount++;
                            }
                        }
                    }
                });
    }

    private int errorCount = 0;

    public void thirdDelivery(OrderDetails.DataBean dataBean) {
        if (!isAutoReceiving) {
            return;
        }
        ThirdItem third = new ThirdItem();
        if (dataBean.getPRODUCT_NAME() != null) {
            for (OrderDetails.DataBean.PRODUCTNAMEBean productnameBean : dataBean.getPRODUCT_NAME()) {
                ThirdItem.ThirdItemItem.UntPrice hkd = new ThirdItem.ThirdItemItem.UntPrice("HKD", Double.valueOf(productnameBean.getPRICE()));
                ThirdItem.ThirdItemItem thirdItemItem;

                if (TextUtil.isNotEmptyOrNullOrUndefined(productnameBean.getPRODUCT_NAME())) {
                    thirdItemItem = new ThirdItem.ThirdItemItem(productnameBean.getPRODUCT_NAME(), hkd);
                } else {
                    thirdItemItem = new ThirdItem.ThirdItemItem("", hkd);
                }
                third.add(thirdItemItem);
            }
        }
        RequestBody requestBody = new FormBody.Builder()
                .add("orderId", dataBean.getID() + "")
                .add("items", GsonUtils.GsonString(third))
                .build();
        mModel.thirdDelivery(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> {
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<ShipAnyOrdersNewBean>(mErrorHandler) {
                    @Override
                    public void onSubscribe(Disposable d) {
                        super.onSubscribe(d);
                        autoDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull ShipAnyOrdersNewBean info) {
                        if (info != null && info.isSuccess()) {
                            //修改訂單狀態
                            updateOrderState(dataBean, ColdChainConstants.ORDER_CONFIRMED);
                        } else {
                            if (errorCount < 5) {
                                thirdDelivery(dataBean);
                                errorCount++;
                            }
                        }
                    }
                });
    }

    public void updateOrderState(OrderDetails.DataBean dataBean, int status) {
        if (!isAutoReceiving) {
            return;
        }
        //添加PRJ
        addPrj(dataBean);
        RequestBody requestBody = new FormBody.Builder()
                .add("memberId", GsaCloudApplication.getMemberId() + "")
                .add("orderId", dataBean.getID() + "")
                .add("status", status + "")
                .add("", GsaCloudApplication.getMemberName() + "")
                .build();
        mModel.updateOrderStatus(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("確認訂單中，請稍候..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<UpdateOrderStatusBean>(mErrorHandler) {
                    @Override
                    public void onSubscribe(Disposable d) {
                        super.onSubscribe(d);
                        autoDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull UpdateOrderStatusBean info) {
                        errorCount = 0;
                        mRootView.refreshOrderState(dataBean.getID());
                        if (ids != null && ids.size() > 0) {
                            findOrderDetails(ids.get(0));
                            ids.remove(0);
                        } else {
                            startToBeConfirmedOrderList(GsaCloudApplication.getRestaurantId());
                        }
                    }
                });
    }

    private void addPrj(OrderDetails.DataBean dataBean) {
        StringBuilder ids = new StringBuilder();
        if (dataBean.getPRODUCT_NAME() != null) {
            for (OrderDetails.DataBean.PRODUCTNAMEBean productnameBean : dataBean.getPRODUCT_NAME()) {
                if (productnameBean.getChild() != null) {
                    for (OrderDetails.DataBean.PRODUCTNAMEBean.ChildBeanX childBeanX : productnameBean.getChild()) {
                        if (childBeanX != 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", dataBean.getID() + "")
                    .add("restaurantId", GsaCloudApplication.getRestaurantId() + "")
                    .add("orderDetailsIds", ids.toString())
                    .build();
            mModel.addPrj(requestBody);
        }
    }

}
