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.OrderListContract;
import com.gingersoft.coldchain_module.mvp.model.bean.OrderList;
import com.gingersoft.coldchain_module.mvp.model.bean.ShipAnyOrdersNewBean;
import com.gingersoft.coldchain_module.mvp.model.bean.ThirdItem;
import com.gingersoft.coldchain_module.mvp.model.bean.UpdateOrderStatusBean;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
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.FragmentScope;
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.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;


@FragmentScope
public class OrderListPresenter extends BasePresenter<OrderListContract.Model, OrderListContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private String TAG = this.getClass().getSimpleName();

    @Inject
    public OrderListPresenter(OrderListContract.Model model, OrderListContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    private List<OrderList.DataBeanX.DataBean> orderList = new ArrayList<>();
    private Disposable disposable;

    public void getOrderList(int restaurantId, int page, String status, String type, String phone) {
        if (disposable != null) {
            if (!disposable.isDisposed()) {
                return;
            }
        }
        RequestBody requestBody = new FormBody.Builder()
                .add("restaurantId", restaurantId + "")
                .add("page", page + "")
                .add("pageSize", "")
                .add("status", status)
                .add("type", type)
                .add("orderNo", "")
                .add("phone", phone)
                .build();
        mModel.getOrderList(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(""))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<OrderList>(mErrorHandler) {
                    @Override
                    public void onSubscribe(Disposable d) {
                        super.onSubscribe(d);
                        disposable = d;
                    }

                    @Override
                    public void onNext(@NonNull OrderList info) {
                        disposable.dispose();
                        disposable = null;
                        if (page == 1) {
                            orderList.clear();
                        }
                        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();
                                mRootView.loadOrderTotalNum(dataBeans.get(dataBeans.size() - 1));

                                dataBeans.remove(dataBeans.size() - 1);
                                orderList.addAll(dataBeans);
                            }
                            mRootView.loadOrderList(orderList);
                        } else {
                            mRootView.loadOrderList(null);
                            if (info != null && TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                                mRootView.showMessage(info.getErrMsg());
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        if (page == 1) {
                            orderList.clear();
                        }
                        mRootView.loadOrderList(null);
                    }
                });
    }

    public void notifyDataByPosition(int position, int state) {
        if (orderList.size() > position) {
            OrderList.DataBeanX.DataBean dataBean = orderList.get(position);
            if (state == ColdChainConstants.ORDER_READ) {
                //已讀
                dataBean.setIsRead(ColdChainConstants.ORDER_READ);
                mRootView.notifyByPosition(position, dataBean);
            } else if (state == ColdChainConstants.LOGISTICS_CANCELLED) {
                //物流已取消
                dataBean.setCurStat(9);
                //物流已取消，狀態只能是待pick up，因為待確認、派送中的訂單是不能取消物流的
                dataBean.setSTATUS(2);
                mRootView.notifyByPosition(position, dataBean);
            } else if (state == ColdChainConstants.ORDER_CANCELLED) {
                //訂單已取消
                mRootView.removeItem(position);
            } else if (state > 0 && state <= 3) {
                dataBean.setIsRead(ColdChainConstants.ORDER_READ);
                dataBean.setSTATUS(state);
                if (state == ColdChainConstants.ORDER_CONFIRMED) {
                    //訂單如已確認，那麼物流狀態也是已通知物流
                    dataBean.setCurStat(1);
                }
                mRootView.notifyByPosition(position, dataBean);
            }
        }
    }

    public void notifyDataPrintStateByPosition(int position, boolean isPrint) {
        if (orderList.size() > position) {
            OrderList.DataBeanX.DataBean dataBean = orderList.get(position);
            dataBean.setIsPrintPdf(isPrint ? 1 : 0);
            mRootView.notifyByPosition(position, dataBean);
        }
    }

    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 onNext(@NonNull OrderDetails info) {
                        if (info != null) {
                            if (info.getData() != null && info.getData().size() > 0) {
                                mRootView.getOrderDetails(info.getData().get(0));
                            } else {
                                if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrorMsg())) {
                                    mRootView.showMessage(info.getErrorMsg());
                                } else {
                                    Log.e(TAG, "獲取訂單詳情失敗");
                                    mRootView.killMyself();
                                }
                            }
                        } else {
                            Log.e(TAG, "獲取訂單詳情失敗");
                            mRootView.killMyself();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        Log.e(TAG, "獲取訂單詳情失敗");
                        mRootView.killMyself();
                    }
                });
    }

    public void thirdDelivery(OrderDetails.DataBean dataBean) {
        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 -> mRootView.showLoading("確認訂單中，請稍候..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<ShipAnyOrdersNewBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull ShipAnyOrdersNewBean info) {
                        if (info != null) {
                            if (info.isSuccess()) {
                                //修改訂單狀態
                                updateOrderState(dataBean, ColdChainConstants.ORDER_CONFIRMED);
                            } else {
                                if (TextUtil.isNotEmptyOrNullOrUndefined(info.getErrMsg())) {
                                    mRootView.showMessage(info.getErrMsg());
                                } else {
                                    mRootView.showMessage("確認訂單失敗");
                                }
                                mRootView.killMyself();
                            }
                        } else {
                            mRootView.showMessage("服務器錯誤");
                            mRootView.killMyself();
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.showMessage("服務器錯誤");
                        mRootView.killMyself();
                    }
                });
    }

    public void updateOrderState(OrderDetails.DataBean dataBean, int status) {
        //添加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 onNext(@NonNull UpdateOrderStatusBean info) {
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.showMessage(t.getMessage());
                        mRootView.killMyself();
                    }
                });
    }

    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);
        }
    }
}
