package com.gingersoft.coldchain_module.mvp.presenter;

import android.app.Application;
import android.util.Log;

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.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.core.user.UserContext;
import com.gingersoft.gsa.cloud.common.core.restaurant.utils.RestaurantExpandInfoUtils;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.common.core.delivery.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.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
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(RestaurantInfoManager.newInstance().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", RestaurantInfoManager.newInstance().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 Disposable autoDisposable;

    public void stopAutoReceivingOrders() {
        if (autoDisposable != null) {
            autoDisposable.dispose();
        }
    }

    /**
     * 獲取待確認訂單(開了自動接單調用此方法接單)
     *
     * @param restaurantId
     */
    public void startToBeConfirmedOrderList(int restaurantId) {
        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);
                                if (dataBeans.size() > 0) {
                                    //獲取訂單詳情
                                    findOrderDetails(dataBeans.get(0).getId());
                                }
                            }
                        }
                    }
                });
    }


    /**
     * 獲取訂單詳情
     */
    public void findOrderDetails(int orderId) {
        //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));
                        }
                    }
                });
    }

    /**
     * 指派到第三方物流配送
     *
     * @param dataBean
     */
    public void thirdDelivery(OrderDetails.DataBean dataBean) {
        //驗證訂單金額是否正確
        if (OrderDetails.verificationAmount(dataBean)) {
            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 onNext(@NonNull ShipAnyOrdersNewBean info) {
                        if (info != null && info.isSuccess()) {
                            //修改訂單狀態
                            updateOrderState(dataBean, ColdChainConstants.ORDER_CONFIRMED);
                        }
                    }
                });
    }

    /**
     * 修改訂單狀態
     *
     * @param dataBean
     * @param status
     */
    public void updateOrderState(OrderDetails.DataBean dataBean, int status) {
        //驗證訂單金額是否正確
        if (OrderDetails.verificationAmount(dataBean)) {
            return;
        }
        //添加PRJ
        addPrj(dataBean);
        RequestBody requestBody = new FormBody.Builder()
                .add("memberId", UserContext.newInstance().getMemberId() + "")
                .add("orderId", dataBean.getID() + "")
                .add("status", status + "")
                .add("", UserContext.newInstance().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 onNext(@NonNull UpdateOrderStatusBean info) {
                        mRootView.refreshOrderState(dataBean.getID());
                    }
                });
    }

    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) {
                            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", dataBean.getID() + "")
                    .add("restaurantId", RestaurantInfoManager.newInstance().getRestaurantId() + "")
                    .add("orderDetailsIds", ids.toString())
                    .build();
            Disposable subscribe = mModel.addPrj(requestBody)
                    .subscribeOn(Schedulers.io()).subscribe(s -> {});
        }
    }

}
