package com.gingersoft.coldchain_module.mvp.presenter;

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

import com.billy.cc.core.component.CC;
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.UpdateRestaurantStateBean;
import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.constans.ExpandConstant;
import com.gingersoft.gsa.cloud.common.constans.PrintConstans;
import com.gingersoft.gsa.cloud.common.core.delivery.OrderDetails;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfo;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.core.restaurant.utils.RestaurantExpandInfoUtils;
import com.gingersoft.gsa.cloud.common.logan.LoganManager;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.common.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.order.order.TakeawayOrder;
import com.gingersoft.gsa.cloud.print.bean.PrintContent;
import com.gingersoft.gsa.cloud.print.bean.adapter.PrintContentAdapter;
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.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;

    public static final int PRINT_COLD_CHAIN_ORDER_SUCCESS = 1;
    public static final int PRINT_COLD_CHAIN_ORDER_FAIL = 2;

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

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

    /**
     * 獲取待確認訂單(開了自動接單調用此方法接單)
     */
    public void startToBeConfirmedOrderList() {
        RequestBody requestBody = new FormBody.Builder()
                .add("restaurantId", RestaurantInfoManager.newInstance().getRestaurantId() + "")
                .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) {
        findOrderDetails(orderId, false);
    }

    /**
     * 獲取訂單詳情
     */
    public void findOrderDetails(int orderId, boolean isOnlyPrint) {
        //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) {
                        LogUtil.d("eee", "凍鏈：findOrderDetails" + orderId + "--漏打印：" + isOnlyPrint);
                        LoganManager.w_network("凍鏈：findOrderDetails" + orderId + "--漏打印：" + isOnlyPrint);
                        if (info != null && info.getData() != null && info.getData().size() > 0) {
                            if (isOnlyPrint) {
                                updateOrderState(info.getData().get(0), ColdChainConstants.ORDER_CONFIRMED);
                            } else {
                                //第三方配送
                                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.parseDouble(productnameBean.getPRICE()));
                ThirdItem.ThirdItemItem thirdItemItem;
                //一級食品
                if (productnameBean.getNum() != null) {
                    thirdItemItem = new ThirdItem.ThirdItemItem(productnameBean.getPRODUCT_NAME(), hkd, Integer.parseInt(productnameBean.getNum()));
                } else {
                    thirdItemItem = new ThirdItem.ThirdItemItem(productnameBean.getPRODUCT_NAME(), hkd);
                }
                third.add(thirdItemItem);
                if (productnameBean.getChild() != null) {
                    for (OrderDetails.DataBean.PRODUCTNAMEBean.ChildBeanX childBeanX : productnameBean.getChild()) {
                        //二級細項
                        String childBeanXPrice = childBeanX.getPRICE();
                        if (childBeanXPrice == null) {
                            childBeanXPrice = "0";
                        }
                        String childBeanXNum = childBeanX.getNum();
                        if (childBeanXNum == null) {
                            childBeanXNum = "0";
                        }
                        third.add(new ThirdItem.ThirdItemItem(childBeanX.getPRODUCT_NAME(), new ThirdItem.ThirdItemItem.UntPrice("HKD", Double.parseDouble(childBeanXPrice)), Integer.parseInt(childBeanXNum)));
                        if (childBeanX.getChild() != null) {
                            for (OrderDetails.DataBean.PRODUCTNAMEBean.ChildBeanX.ChildBean childBean : childBeanX.getChild()) {
                                //三級細項
                                String childBeanPrice = childBean.getPRICE();
                                if (childBeanPrice == null) {
                                    childBeanPrice = "0";
                                }
                                String childBeanNum = childBean.getNum();
                                if (childBeanNum == null) {
                                    childBeanNum = "0";
                                }
                                third.add(new ThirdItem.ThirdItemItem(childBean.getPRODUCT_NAME(), new ThirdItem.ThirdItemItem.UntPrice("HKD", Double.parseDouble(childBeanPrice)), Integer.parseInt(childBeanNum)));
                            }
                        }
                    }
                }
            }
        }
        LogUtil.d("eee", "調用第三方物流接口開始");
        LoganManager.w_network("凍鏈：調用第三方物流接口開始");
        //第三方物流
        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()) {
                            LogUtil.d("eee", "調用第三方物流接口結束");
                            //修改訂單狀態
                            dataBean.setTakeFoodCode(info.getData().getTakeFoodCode());
                            updateOrderState(dataBean, ColdChainConstants.ORDER_CONFIRMED);
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        LoganManager.w_network("凍鏈：調用第三方物流接口出錯：" + t.getMessage());
                    }
                });
    }

    private void printColdChainOrder(OrderDetails.DataBean dataBean) {
        if (RestaurantExpandInfoUtils.getValue(ExpandConstant.AutoPrinterPaper, true)) {
            //打印凍鏈上菜紙
            dataBean.setOrderType(8);
            TakeawayOrder.getInstance().getShoppingCart().setDeliveryAndPickupData(dataBean);
            PrintContentAdapter contentAdapter = new PrintContentAdapter();
            PrintContent printContent = contentAdapter.adaptationPrintTakeawayFormContent(dataBean);
            LoganManager.w_printer(TAG, "凍鏈：打印上菜紙");
            CC.obtainBuilder(ComponentName.COMPONENT_PRINT)
                    .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_OTHER_ORDER)
                    .addParam(PrintConstans.PRINT_CONTENT, printContent)
                    .addParam(PrintConstans.PRINT_ORDER_NO, dataBean.getORDER_NO())
                    .addParam(PrintConstans.PRINT_SHOW_LOADING, false)
                    .setActionName("printActivity")
                    .build()
                    .callAsyncCallbackOnMainThread((cc, result) -> {
                        if (result.isSuccess()) {
                            //打印成功
                            updatePrintOrderStatus(dataBean.getID(), PRINT_COLD_CHAIN_ORDER_SUCCESS);
                        } else {
                            updatePrintOrderStatus(dataBean.getID(), PRINT_COLD_CHAIN_ORDER_FAIL);
                        }
                        TakeawayOrder.getInstance().getShoppingCart().setDeliveryAndPickupData(null);
                    });
        }
    }

    /**
     * 修改訂單狀態
     *
     * @param dataBean
     * @param status
     */
    public void updateOrderState(OrderDetails.DataBean dataBean, int status) {
        //驗證訂單金額是否正確
        if (OrderDetails.verificationAmount(dataBean)) {
            return;
        }
        Log.e("eee", "取餐碼：" + dataBean.getTakeFoodCode());
        //添加PRJ
        addPrj(dataBean);
        //打印凍鏈上菜紙
        printColdChainOrder(dataBean);
        //再次去獲取待確認訂單列表
        startToBeConfirmedOrderList();
        //修改訂單狀態
        //後台會修改狀態，這裡就不修改
//        RequestBody requestBody = new FormBody.Builder()
//                .add("memberId", UserContext.newInstance().getMemberId() + "")
//                .add("orderId", dataBean.getID() + "")
//                .add("status", status + "")
//                .add("", UserContext.newInstance().getMemberName())
//                .build();
//        LogUtil.w("eee", "修改訂單狀態開始----start");
//        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) {
//                        LogUtil.w("eee", "修改訂單狀態結束----end----" + info.toString());
//                        mRootView.refreshOrderState(dataBean.getID());
//                        //打印凍鏈上菜紙
//                        printColdChainOrder(dataBean);
//                    }
//                });
    }

    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();
            LogUtil.i("eee", "添加prj");
            Disposable subscribe = mModel.addPrj(requestBody)
                    .subscribeOn(Schedulers.io()).subscribe(s -> {
                    });
        }
    }

    /**
     * 獲取未打印的訂單列表
     */
    public void getNotPrintedOrderList() {
        mModel.getNotPrintedOrderList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info.isSuccess()) {
                            LogUtil.i("eee", "獲取未打印列表" + info.getData().toString());
                            LoganManager.w_network("凍鏈：getNotPrintedOrderList");
                            List<Integer> ids = GsonUtils.jsonToList(info.getData(), Integer.class);
                            if (ids.size() > 0) {
                                findOrderDetails(ids.get(0), true);
                            }
                        }
                    }
                });
    }

    /**
     * 獲取未打印的訂單列表
     *
     * @param orderId
     * @param printState 打印上菜紙狀態：0 未打印，1 打印成功，2 打印失敗
     */
    public void updatePrintOrderStatus(int orderId, int printState) {
        RequestBody requestBody = new FormBody.Builder()
                .add("orderId", orderId + "")
                .add("printStatus", printState + "")
                .build();
        mModel.updatePrintOrderStatus(requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        Log.e("eee", "修改訂單" + orderId + "打印狀態結束：" + printState);
                    }
                });
    }
}
