package com.gingersoft.gsa.cloud.table.mvp.presenter;

import android.app.Application;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.constans.ExpandConstant;
import com.gingersoft.gsa.cloud.common.constans.FoodSummaryConstans;
import com.gingersoft.gsa.cloud.common.constans.GoldConstants;
import com.gingersoft.gsa.cloud.common.constans.PrintConstans;
import com.gingersoft.gsa.cloud.common.core.member.MemberInfo;
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.core.table.TableBean;
import com.gingersoft.gsa.cloud.common.core.table.TableExtBean;
import com.gingersoft.gsa.cloud.common.logan.LoganManager;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.database.bean.Discount;
import com.gingersoft.gsa.cloud.database.bean.Function;
import com.gingersoft.gsa.cloud.order.bean.discount.CouponDiscountBean;
import com.gingersoft.gsa.cloud.order.bean.response.CouponDiscountResponse;
import com.gingersoft.gsa.cloud.order.bean.response.OrderResponse;
import com.gingersoft.gsa.cloud.order.billItem.BillItem;
import com.gingersoft.gsa.cloud.order.billItem.DiscountItem;
import com.gingersoft.gsa.cloud.order.commodity.OrderDetail;
import com.gingersoft.gsa.cloud.order.discount.CouponDiscount;
import com.gingersoft.gsa.cloud.order.discount.MemberDiscount;
import com.gingersoft.gsa.cloud.order.discount.NomalDiscount;
import com.gingersoft.gsa.cloud.order.order.BaseOrder;
import com.gingersoft.gsa.cloud.order.order.DoshokuOrder;
import com.gingersoft.gsa.cloud.print.PrinterUtils;
import com.gingersoft.gsa.cloud.print.bean.PrintContent;
import com.gingersoft.gsa.cloud.print.bean.adapter.PrintContentAdapter;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.mvp.contract.OrderContentContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.request.AddOrderRequest;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.request.CreateOrderRequest;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.response.BaseOrderResponse;
import com.gingersoft.gsa.cloud.table.mvp.action.discount.BillDiscountAction;
import com.gingersoft.gsa.cloud.table.mvp.model.utils.OrderAssemblyUtil;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.MealStandActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.OrderContentActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.OrderPayActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.TableActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.BillItemAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.OrderTopFunctionAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.SelectMealAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.DiscountDialog;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.SplitTableDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.BaseRetryDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.xuexiang.rxutil2.rxjava.RxJavaUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
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.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.RequestBody;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 01/09/2020 19:23
 * <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 OrderContentPresenter extends BaseOrderPresenter<OrderContentContract.Model, OrderContentContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private OrderContentActivity IActivity;

    private OrderTopFunctionAdapter mOrderTopFunctionAdapter;
    private List<Function> mFunctionList = new ArrayList<>();

    /**
     * 分檯弹窗
     */
    private SplitTableDialog mSplitTableDialog;
    private DiscountDialog.Builder mDiscountDialog;
    /**
     * 整單折扣邏輯
     */
    private BillDiscountAction mNomalDiscountAction;

    private Disposable mGetTablesDataDisposable;
    private Disposable mTablesPollingDisposable;

    @Inject
    public OrderContentPresenter(OrderContentContract.Model model, OrderContentContract.View rootView) {
        super(model, rootView);
        this.IActivity = (OrderContentActivity) rootView;
        if (mDoshokuOrder != null && !mDoshokuOrder.isModifyOrder()) {
            //转移食品可多选
            mSelectMealAdapter.setSelectedMode(SelectMealAdapter.MULTIPLE_SELECTED);
        }
        mNomalDiscountAction = new BillDiscountAction(IActivity, new BillDiscountAction.OnCallBackListener() {

            @Override
            public void exclusiveRemoveOthers(List<NomalDiscount> nomalDiscountList) {
                mShoppingCart.delAllNomalDiscountList(nomalDiscountList);
            }

            @Override
            public void preformAddDiscount(Discount discount) {
                mShoppingCart.addMultyDiscount(mShoppingCart.createNomalDiscount(discount, BillItem.BILL_ITEM_NO_ORDER_STATUS));
                updateBillInfo();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
        if (mNomalDiscountAction != null) {
            mNomalDiscountAction.destroy();
        }
        stopTablePolling();
    }

    public void initAdapter() {
        if (mOrderTopFunctionAdapter == null) {
            mOrderTopFunctionAdapter = new OrderTopFunctionAdapter(IActivity, mFunctionList);
            mRootView.setTopFunctionAdapter(mOrderTopFunctionAdapter);
        }
        if (mBillItemAdapter != null) {
            mRootView.setOrderDetailAdapter(mBillItemAdapter);
        }
        mRootView.setFoodAdapter(mSelectMealAdapter);

        setPrinterMachineName();
    }

    public void initItemListener() {
        mOrderTopFunctionAdapter.setOnClickListener(new OrderTopFunctionAdapter.OnClickListener() {
            @Override
            public void onItemClick(View v, Function function) {

                LoganManager.w_tableMode(TAG, LoganManager.EVENT_CLICK, function.getResName());

                mRootView.recordOperat(true);

                switch (function.getResName()) {
                    case "送單":
                        sendOrder(false, null);
                        break;
                    case "印單":
                        if (!canPrint()) {
                            return;
                        }
                        if (BaseOrder.isCurrentOrderType(FoodSummaryConstans.TAKEAWAY_TYPE)) {
                            //TODO 外賣新訂單印單
                            printOrder(DoshokuOrder.getInstance().getOpenTableInfo().getId(), false);
                            return;
                        }
                        if (hasNesOrderFoods() || getNewDiscount() != null) {
                            //有未送單食品先送單
                            sendOrder(true, null);
                        } else {
                            printOrder(DoshokuOrder.getInstance().getOpenTableInfo().getId(), false);
                        }
                        break;
                    case "結賬":
//                        if (!canPay()) {
//                            return;
//                        }
                        if (hasNesOrderFoods() || getNewDiscount() != null || hasModifyFoods() || mDoshokuOrder.needUpdateMemberInfo()) {
                            Class[] parameterTypes = {boolean.class, Class.class};
                            Object[] parameters = {false, OrderPayActivity.class};
                            CommonTipDialog.showDoubtDialog(IActivity, "賬單已變化，是否送單后去結賬", BaseOrderPresenter.class, mBaseOrderPresenter,
                                    "sendOrder", parameterTypes, parameters);
                            //有未送單食品先送單
//                            sendOrder(false, OrderPayActivity.class);
                        } else {
                            mRootView.startActivityForResult(OrderContentActivity.BILL_CODE, OrderPayActivity.class, null);
                        }
                        break;
                    case "轉移":
                        if (!canTransfer()) {
                            return;
                        }
                        mRootView.showTransferFoodLayout();
                        break;
                    case "折扣":
                        if (!canDiscount()) {
                            return;
                        }
                        showDiscountDialog();
                        break;
                    case "送單信息":
                        CC.obtainBuilder(ComponentName.COMPONENT_DELIVERYPICK)
                                .setActionName("SendOrder")
                                .build()
                                .call();
                        break;
                }
            }

            @Override
            public boolean onItemLongClick(View v, Function datasBean) {
                LoganManager.w_tableMode(TAG, LoganManager.EVENT_LONG_CLICK, datasBean.getResName());
                if (datasBean.getResName().equals("印單") || datasBean.getResName().equals("送單")) {
                    PrinterUtils.switchPrintMethod(IActivity, datasBean, mOrderTopFunctionAdapter);
                }
                return false;
            }
        });
        mBillItemAdapter.setOnItemClickListener(new BillItemAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(BillItem datasBean, int position) {

            }

            @Override
            public void onItemDeleteClick(BillItem datasBean, int position) {
                addDeleteDiscountIdByType(datasBean);
                removeBillItemByPosition(position);
            }
        });
    }

    /**
     * 跟进折扣类型将Id加入到删除列表,注：会员折扣不可删除
     *
     * @param item
     */
    private void addDeleteDiscountIdByType(BillItem item) {
        if (item instanceof DiscountItem) {
            if (item.getType() == BillItem.NOMAL_DISCOUNT_TYPE) {
                NomalDiscount nomalDiscount = (NomalDiscount) ((DiscountItem) item).getDiscount();
                mDoshokuOrder.addDeleteDiscountId(nomalDiscount.getDiscount().getDiscountRecordId());
            } else if (item.getType() == BillItem.COUPON_DISCOUNT_TYPE) {
                CouponDiscount couponDiscount = (CouponDiscount) ((DiscountItem) item).getDiscount();
                mDoshokuOrder.addDeleteDiscountId(couponDiscount.getCouponDiscountId());
            }
        }
    }

    public void initTopFunctionData() {
        if (mFunctionList.size() > 0) {
            mFunctionList.clear();
        }
        if (BaseOrder.isTableToMeal()) {
            if (mDoshokuOrder.isModifyOrder()) {
                //修改訂單隱藏送單，印單功能
                mFunctionList.add(new Function("結賬", Color.parseColor("#FFFFFF"), Color.parseColor("#DC0000"), 24));
                mFunctionList.add(new Function("折扣", Color.parseColor("#FFFFFF"), Color.parseColor("#008577"), 24));
            } else {
//                List<Function> functions = FunctionManager.getDefault().getFunctionByResModule(GsaCloudApplication.getAppContext(), ComponentTable.table.class, ComponentTable.table.order, "order");
//                for (int i = 0; i < functions.size(); i++) {
//                    if (functions.get(i).getParentId() == 0) {
//                        functions.remove(i);
//                    }
//                }
//                if (functions.size() > 0) {
//                    mFunctionList.addAll(functions);
//                } else {
                mFunctionList.add(new Function("送單", Color.parseColor("#FFFFFF"), Color.parseColor("#008131"), 24));
                mFunctionList.add(new Function("印單", Color.parseColor("#FFFFFF"), Color.parseColor("#FF8E04"), 24));
                mFunctionList.add(new Function("結賬", Color.parseColor("#FFFFFF"), Color.parseColor("#DC0000"), 24));
                mFunctionList.add(new Function("轉移", Color.parseColor("#FFFFFF"), Color.parseColor("#FF4B9DFA"), 24));
                mFunctionList.add(new Function("折扣", Color.parseColor("#FFFFFF"), Color.parseColor("#008577"), 24));
//                }
            }
        } else if (BaseOrder.isCurrentOrderType(FoodSummaryConstans.TAKEAWAY_TYPE)) {
            mFunctionList.add(new Function("折扣", Color.parseColor("#FFFFFF"), Color.parseColor("#008577"), 24));
            mFunctionList.add(new Function("印單", Color.parseColor("#FFFFFF"), Color.parseColor("#FF8E04"), 24));
            mFunctionList.add(new Function("送單信息", Color.parseColor("#FFFFFF"), Color.parseColor("#008131"), 24));
        }
    }

    public void setPrinterMachineName() {
        if (!TextUtils.isEmpty(PrinterUtils.printMachineCode)) {
            for (int i = 0; i < mFunctionList.size(); i++) {
                Function function = mFunctionList.get(i);
                if (function.getResName().equals("印單")) {
                    function.setLable(PrinterUtils.printMachineCode);
                    mOrderTopFunctionAdapter.notifyItemChanged(i);
                    break;
                }
            }
        }
    }

    @Override
    public void createOrder(boolean isPrint, Class<?> afterToActivity) {
        CreateOrderRequest request = getCreateOrderRequest(getOrderFoodLists());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(request));
        String json = GsonUtils.GsonString(request);
        mModel.createOrder(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseOrderResponse>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseOrderResponse info) {
                        sendOrderRespose(info, isPrint, afterToActivity);
                    }
                });
    }

    @Override
    public void addOrderFood(boolean isPrint, Class<?> afterToActivity) {
        List<OrderDetail> foodLists = getOrderFoodLists();
        for (OrderDetail food : foodLists) {
            food.setOrderId(mDoshokuOrder.getOrderId());
        }
        AddOrderRequest addOrderRequest = getAddOrderRequest(foodLists);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonUtils.GsonString(addOrderRequest));
        String json = GsonUtils.GsonString(addOrderRequest);
        mModel.addFood(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseOrderResponse>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull BaseOrderResponse info) {
                        sendOrderRespose(info, isPrint, afterToActivity);
                    }
                });
    }

    private void sendOrderRespose(BaseOrderResponse info, boolean isPrint, Class<?> afterToActivity) {
        if (info == null) {
            if (isPrint) {
                printOrder(mTableInfo.getId(), true);
            } else {
                if (!hasNesOrderFoods()) {
                    //未新增食品點擊送單 後台不讓過直接提示即可，不調用打印
                    mRootView.showMessage("送單成功");
//                                    mRootView.sendSuccess();
                } else {
                    mRootView.showMessage(info.getErrMsg());
                }
            }
        } else {
            if (isPrint) {
                printOrder(mTableInfo.getId(), true);
            } else {
                mRootView.showMessage("送單成功");
                //刷新食品列表
                if (afterToActivity != null) {
                    updateOrderDetails(info);
                }
                printSendOrder(afterToActivity);
            }
        }
    }

    /**
     * 送單打印上菜纸
     */
    private void printSendOrder(Class<?> afterToActivity) {
        if (afterToActivity != null) {
            mRootView.startActivityForResult(OrderContentActivity.BILL_CODE, afterToActivity, null);
        }
        if (RestaurantExpandInfoUtils.getValue(ExpandConstant.AutoPrinterPaper, true)) {
            if (RestaurantExpandInfoUtils.getValue(ExpandConstant.MergeSendFood, true)) {
                //合并主食品
                mergeMainFoodNumber(mOrderMealList);
            }
            //賬單內容送單
            if (DoshokuOrder.getInstance().getNewFoodList() == null || DoshokuOrder.getInstance().getNewFoodList().size() <= 0) {
                //沒有新的食品時，不打印送單
                if (afterToActivity == null) {
                    mRootView.sendSuccess();
                    mAppManager.killActivity(MealStandActivity.class);
                }
                return;
            }
            //賬單內容送單
            PrintContent printContent = new PrintContentAdapter().adaptationSendOrderPaperContent(DoshokuOrder.getInstance(), mTableInfo);

            CC.obtainBuilder(ComponentName.COMPONENT_PRINT)
                    .setActionName("printActivity")
                    .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_SERVE)
                    .addParam(PrintConstans.PRINT_CONTENT, printContent)
                    .addParam(PrintConstans.PRINT_ORDER_NO, DoshokuOrder.getInstance().getOrderNo())
                    .build()
                    .callAsyncCallbackOnMainThread((cc, result) -> {
                        if (result.isSuccess()) {
                        } else {
                            mRootView.showMessage("打印失敗");
                        }
                        if (afterToActivity == null) {
                            mRootView.sendSuccess();
                            mAppManager.killActivity(MealStandActivity.class);
                        }
                    });
        } else {
            if (afterToActivity == null) {
                mRootView.sendSuccess();
                mAppManager.killActivity(MealStandActivity.class);
            }
        }
    }

    public void printOrder(long tableId, boolean isSend) {
        RequestBody requestBody = new FormBody.Builder()
                .add("tableId", tableId + "")
                .add("tableNumber", mTableInfo.getTableNumber())
                .build();
        mModel.printOrder(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseOrderResponse>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseOrderResponse info) {
                        if (info != null && info.isSuccess()) {
                            if (RestaurantExpandInfoUtils.getValue(ExpandConstant.MergeSendFood, true)) {
                                //合并主食品
                                mergeMainFoodNumber(mOrderMealList);
                            }

                            PrintContent printContent = new PrintContentAdapter().adaptationPrintSlipContent(DoshokuOrder.getInstance(), mTableInfo);

                            CC.obtainBuilder(ComponentName.COMPONENT_PRINT)
                                    .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_SLIP)//印單
                                    .addParam(PrintConstans.PRINT_CONTENT, printContent)
                                    .addParam(PrintConstans.PRINT_ORDER_NO, DoshokuOrder.getInstance().getOrderNo())
                                    .setActionName("printActivity")
                                    .build()
                                    .callAsyncCallbackOnMainThread((cc, result) -> {
                                        Log.e("error", "是否成功打印：" + result.isSuccess());
                                        if (result.isSuccess()) {
                                            //打印成功
                                            mRootView.showMessage("打印成功!");
                                        } else {
                                            mRootView.showMessage("打印失敗!");
                                        }
                                        //不管打印是否成功，都需要退出當前頁面
                                        mRootView.printSuccess();
                                    });
                            //打印
                        } else {
                            mRootView.showMessage("印單失敗!");
                            if (isSend) {
                                //印單失敗但提交新食品成功,更新一遍訂單數據
                                loadOrder(mDoshokuOrder.getOrderId());
                            }
                        }
                    }
                });
    }

    public void queryCoupon(Long memberId, long couponMemberId, String couponNo, int restaurantId) {
        if (mDoshokuOrder == null) {
            return;
        }
        int tableId = mDoshokuOrder.getOpenTableInfo().getId();
        mModel.queryCoupon(tableId, memberId, couponMemberId, couponNo, restaurantId)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null) {
                                CouponDiscountResponse couponResult = JsonUtils.parseObject(info.getData(), CouponDiscountResponse.class);
                                if (couponResult != null) {
                                    boolean updateBillItem = false;
                                    MemberInfo memberInfo = couponResult.getMemberInfo();
                                    if (memberInfo != null) {
                                        updateBillItem = true;
                                        mDoshokuOrder.setMemberInfo(memberInfo);
                                        mShoppingCart.addMultyDiscount(mShoppingCart.createMemberDiscount(memberInfo, BillItem.BILL_ITEM_NO_ORDER_STATUS));
                                    }
                                    CouponDiscountBean couponBean = couponResult.getCouponBean();
                                    if (couponBean != null) {
                                        if (!addMemberCouponConditionFilter(couponBean)) {
                                            return;
                                        }
                                        updateBillItem = true;
                                        mShoppingCart.addMultyDiscount(mShoppingCart.createCouponDiscount(couponBean, BillItem.BILL_ITEM_NO_ORDER_STATUS));
                                    }
                                    if (updateBillItem) {
                                        updateBillInfo();
                                    }
                                }
                            } else {
                                mRootView.showMessage(info.getErrMsg());
                            }
                        } else {
                            if (info.getErrCode().equals(CouponDiscountResponse.ERROR_CODE_0001)) {
                                mRootView.showMessage("會員已在其他餐廳使用");
                            } else if (info.getErrCode().equals(CouponDiscountResponse.ERROR_CODE_0002)) {
                                mRootView.showMessage("請掃描當前品牌的優惠券碼");
                            } else if (info.getErrCode().equals(CouponDiscountResponse.ERROR_CODE_0003)) {
                                mRootView.showMessage("請掃描當前會員的優惠券碼");
                            } else {
                                mRootView.showMessage(info.getErrMsg());
                            }
                        }
                    }
                });
    }

    public void loadOrder(long orderId) {
        mModel.loadOrder(orderId)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseOrderResponse>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseOrderResponse info) {
                        updateOrderDetails(info);
                    }
                });
    }

    public void getTables(boolean show, RefreshLayout refreshLayout) {
        int restaurantId = RestaurantInfoManager.newInstance().getRestaurantId();
        mModel.getTables(restaurantId)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    if (show && refreshLayout == null) {
                        mRootView.showLoading(null);
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<TableBean>(mErrorHandler) {

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

                    @Override
                    public void onNext(@NonNull TableBean tableBean) {
                        if (!IActivity.isRefreshData()) {
                            return;
                        }
                        if (tableBean.isSuccess()) {
                            List<TableBean.DataBean> tableBeanData = tableBean.getData();
                            if (tableBeanData != null && tableBeanData.size() > 0) {
                                sortTableList(tableBeanData);
                                mRootView.returnTableList(tableBeanData);
                            } else {
                                mRootView.getCurrentTableFragment().showEmptyView(true, 0, null);
                            }
                        } else {
                            if (show) {
                                mRootView.getCurrentTableFragment().showMessage(tableBean.getErrMsg());
                            }
                            mRootView.getCurrentTableFragment().showEmptyView(false, 0, null);
                        }
                        resetRefreshLayout();
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.getCurrentTableFragment().showEmptyView(false, 0, t);
                        resetRefreshLayout();
                    }

                    private void resetRefreshLayout() {
                        if (refreshLayout != null) {
                            refreshLayout.finishRefresh();
                            refreshLayout.resetNoMoreData();
                        }
                    }

                    private void sortTableList(List<TableBean.DataBean> dataBeanList) {
                        Comparator c = new Comparator<TableBean.DataBean>() {
                            @Override
                            public int compare(TableBean.DataBean o1, TableBean.DataBean o2) {
                                Integer sort1 = o1.getSort();
                                Integer sort2 = o2.getSort();
                                return sort1.compareTo(sort2);
                            }
                        };
                        Collections.sort(dataBeanList, c);
                    }
                });
    }

    public void getTable(TableBean.DataBean dataBean) {
        mModel.getTable(dataBean.getId(), dataBean.getTableNumber())
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseResult result) {
                        if (result.isSuccess()) {
                            TableBean.DataBean tableBean = JsonUtils.parseObject(result.getData(), TableBean.DataBean.class);
                            if (tableBean != null) {
                                if (tableBean.getUseStatus() == 0) {
                                    String msg = "轉移到" + tableBean.getTableName() + "號檯?";
                                    Class[] parameterTypes = {TableBean.DataBean.class};
                                    Object[] parameters = {tableBean};
                                    CommonTipDialog.showDoubtDialog(IActivity, msg, OrderContentPresenter.class, OrderContentPresenter.this,
                                            "transferFood", parameterTypes, parameters);
                                } else {
                                    mRootView.showMessage(tableBean.getTableName() + "號檯操作中");
                                }
                                mRootView.setTransferTableName(tableBean.getTableName());
                            }
                        } else {
                            mRootView.showMessage(result.getErrMsg());
                        }
                    }
                });
    }

    private void transferFood(TableBean.DataBean dataBean) {

        String ids = getSelectedOldFoodIds();
        if (TextUtils.isEmpty(ids)) {
            return;
        }

        RequestBody requestBody = new FormBody.Builder()
                .add("tableId", String.valueOf(mTableInfo.getId()))
                .add("targetId", String.valueOf(dataBean.getId()))
                .add("tableNumber", mTableInfo.getTableNumber())
                .add("targetTableNumber", dataBean.getTableNumber())
                .add("orderId", String.valueOf(mDoshokuOrder.getOrderId()))
                .add("orderDetailsIds", ids)
                .build();

        mModel.transferFood(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseOrderResponse>(mErrorHandler) {

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

                        if (info == null) {
                            mRootView.showMessage("轉移失敗");
                            return;
                        }

                        if (info.isSuccess()) {

                            mRootView.showMessage("轉移成功");

                            updateOrderDetails(info);
                            updateBillInfo();
                            IActivity.backPressed();
                        } else {
                            mRootView.showMessage(info.getErrMsg());
                        }
                    }
                });
    }


    public void getSplitTables(int tableId) {
        mModel.getSplitTables(tableId)
                .subscribeOn(Schedulers.io())
//                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
//                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onSubscribe(Disposable d) {
                        super.onSubscribe(d);
                        mSplitTableDialog.clearItems();
                        mSplitTableDialog.setProgressVisibility(true);
                    }

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null) {

                                TableExtBean tableExtBean = JsonUtils.parseObject(info.getData(), TableExtBean.class);

                                List<TableBean.DataBean> dataBeanList = assemblyTableExts(tableExtBean.getRestaurantTable(), tableExtBean.getRestaurantTableExtList());

                                mSplitTableDialog.addItems(dataBeanList);
                                mSplitTableDialog.notifyDataSetChanged();
                            } else {
                                mSplitTableDialog.showEmptyView(true, 0, null);
                            }
                        } else {
                            mSplitTableDialog.showEmptyView(false, 0, null);
                        }
                        mSplitTableDialog.setProgressVisibility(false);
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mSplitTableDialog.setProgressVisibility(false);
                        mSplitTableDialog.showEmptyView(false, 0, t);
                    }

                    private List<TableBean.DataBean> assemblyTableExts(TableBean.DataBean mainTable, List<TableExtBean.DataBean> restaurantTableExtList) {
                        List<TableBean.DataBean> dataBeans = new ArrayList<>();
                        //添加主檯
                        dataBeans.add(mainTable);
                        //添加分檯
                        for (TableExtBean.DataBean dataBean : restaurantTableExtList) {
                            dataBeans.add(TableBean.splitTableTransformTable2(mainTable, dataBean));
                        }
                        return dataBeans;
                    }
                });
    }

    public void showSplitTableDialog(int tableId) {
        if (mSplitTableDialog == null) {
            mSplitTableDialog = new SplitTableDialog(IActivity);
            mSplitTableDialog.setOnClickListener(new SplitTableDialog.OnClickListener() {
                @Override
                public void onItemClick(SplitTableDialog dialog, TableBean.DataBean dataBean, int position) {
                    mSplitTableDialog.closeDialog();
                    //獲取餐檯狀態
                    getTable(dataBean);
                }
            });
            mSplitTableDialog.setOnRetryListener(new BaseRetryDialog.OnRetryListener() {

                @Override
                public void onRetryClick() {
                    getSplitTables(tableId);
                }
            });
        }
        mSplitTableDialog.setMainTableId(tableId);
        mSplitTableDialog.build().show();
        getSplitTables(tableId);
    }

    private void showDiscountDialog() {
        if (mDiscountDialog == null) {
            mDiscountDialog = new DiscountDialog.Builder(IActivity);
            mDiscountDialog.setCanScan(true);
            mDiscountDialog.setOnClickListener(new DiscountDialog.Builder.OnClickListener() {
                @Override
                public void onItemClick(Discount item, int position) {
                    if (item.getMinBillAmount() > mShoppingCart.getWholeAmount()) {
                        //小於最小賬單金額
                        mRootView.showMessage("小於最小賬單金額" + cashStr + item.getMinBillAmount() + " 無法使用此折扣");
                        return;
                    }
                    mNomalDiscountAction.setNomalDiscountList(mShoppingCart.getNomalDiscoutByMultyDiscountList());
                    mNomalDiscountAction.action(item);
                }

                @Override
                public void onScan() {
                    toScanActivity();
                }
            });
        }
        List<Discount> discountList;
        if (BaseOrder.isCurrentOrderType(FoodSummaryConstans.TAKEAWAY_TYPE)) {
            discountList = mModel.queryDB_DiscountList(Discount.discount_scope_bill, Discount.ORDER_TYPE_TAKEAWAY);
        } else {
            discountList = mModel.queryDB_DiscountList(Discount.discount_scope_bill, Discount.ORDER_TYPE_MEAL_STAND);
        }

        mDiscountDialog.addItems(discountList);
        mDiscountDialog.build().show();
    }

    /**
     * 更新訂單詳情
     *
     * @param info
     */
    private void updateOrderDetails(BaseOrderResponse info) {
        if (mDoshokuOrder != null && info.getData() != null) {

            mTableInfo.setPerson(info.getData().getPerson());
            mTableInfo.setCreateTime(info.getData().getCreateTime());

            mDoshokuOrder.setOpenTableInfo(mTableInfo);
            mDoshokuOrder.setOrderPlaced(info.getData());

            if (info.getData().getOrderDetails() != null) {
                //组装食品信息
                List<OrderDetail> orderDetailList = OrderAssemblyUtil.assemblyOrder(OrderDetail.orderTransOrderDetails(info.getData().getOrderDetails()));

                mDoshokuOrder.setNewFoodList(orderDetailList);

                mOrderMealList.clear();
                mOrderMealList.addAll(orderDetailList);
                mSelectMealAdapter.notifyDataSetChanged();
                mSelectMealAdapter.setIndex();
            }

            for (BillItem billItem : mBillItemList) {
                //將已有折扣 服務費狀態改為已送單
                billItem.setStatus(BillItem.BILL_ITEM_ORDER_SENT_STATUS);
                billItem.setTextColor(ArmsUtils.getColor(IActivity, R.color.theme_black));
            }
            mBillItemAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 轉移條件過濾
     *
     * @return
     */
    public boolean transferFoodConditionFilter(long memberId) {
        List<OrderDetail> oldOrderDetails = getSelectedOldFood();
        for (OrderDetail item : oldOrderDetails) {
            //積分食品轉移-》目標檯不是會員檯-》提示不可轉移
            if ((item.getPointsAdd() != 0 || item.getPointsRedeem() != 0) && memberId == 0) {
                String msg = "積分食品轉移,目標檯不是會員檯,不可轉移!";
                CommonTipDialog.showSurpisedDialog(IActivity, msg, OrderContentPresenter.class, OrderContentPresenter.this,
                        "", null, null);
                return false;
            }
        }
        return true;
    }

    /**
     * 會員優惠券使用條件
     *
     * @param coupon
     * @return
     */
    private boolean addMemberCouponConditionFilter(CouponDiscountBean coupon) {
        if (coupon.getSpend() != null) {
            //配置了消費滿減
            double toodTotal = getFoodTotal();
            if (toodTotal < coupon.getSpend().doubleValue()) {
                //未滿足消費滿條件
                String msg = "消費金額未滿足使用條件,最低消費[$" + toodTotal + "]";
                CommonTipDialog.showSurpisedDialog(IActivity, msg, OrderContentPresenter.class, OrderContentPresenter.this,
                        "", null, null);
                return false;
            }
        }
        return true;
    }

    public void removeBillItemByPosition(int index) {
        if (index < mBillItemList.size()) {
            BillItem billItem = mBillItemList.get(index);
            if (billItem instanceof DiscountItem) {
                //刪除折扣列表對應數據
                mShoppingCart.delMultyDiscount(((DiscountItem) billItem).getDiscount());
            }
            updateBillInfo();
        }
    }

    /**
     * 修改訂單包含修改或刪除過的的食品
     *
     * @return
     */
    private boolean hasModifyFoods() {
        for (OrderDetail orderDetail : getOrderFoodLists()) {
            if (orderDetail.isModify()) {
                return true;
            }
        }
        return false;
    }

    private boolean canPrint() {
        if (getFoodCount() == 0) {
            mRootView.showMessage("沒有食品，不能印單");
            return false;
        }
        return true;
    }

    private boolean canPay() {
        if (getFoodCount() == 0) {
            mRootView.showMessage("沒有食品，不能結賬");
            return false;
        }
        return true;
    }

    private boolean canTransfer() {
        if (getFoodCount() == 0 || mSelectMealAdapter.getSelect_position() == -1) {
            mRootView.showMessage("請選擇轉移食品");
            return false;
        }
        if (mOrderMealList.get(mSelectMealAdapter.getSelect_start_position()).isNew() == true) {
            mRootView.showMessage("請選擇已送單食品轉移");
            return false;
        }
        return true;
    }

    private boolean canDiscount() {
        if (getFoodCount() == 0) {
            mRootView.showMessage("請先選擇食品!");
            return false;
        }
        return true;
    }

    public void startTablePolling() {
        if (mTablesPollingDisposable == null) {
            mTablesPollingDisposable = RxJavaUtils.polling(GoldConstants.refreshTime)
                    .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long aLong) throws Exception {
                            if (TableActivity.isRefreshData) {
                                getTables(false, null);
                            }
                        }
                    });
        }
    }

    public void stopTablePolling() {
        if (mTablesPollingDisposable != null && !mTablesPollingDisposable.isDisposed()) {
            mTablesPollingDisposable.dispose();
            mTablesPollingDisposable = null;
        }
    }

    public Disposable getGetTablesDataDisposable() {
        return mGetTablesDataDisposable;
    }

    public List<Function> getFunctionList() {
        return mFunctionList;
    }

    public void closeDiscountDialog() {
        if (mDiscountDialog != null) {
            mDiscountDialog.closeDialog();
        }
    }
}
