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

import android.app.Application;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.aspectj.XClickUtil;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.base.common.bean.BillOrderMoney;
import com.gingersoft.gsa.cloud.base.common.bean.OrderBean;
import com.gingersoft.gsa.cloud.base.common.bean.OrderDetail;
import com.gingersoft.gsa.cloud.base.common.bean.TableBean;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.OpenTableManage;
import com.gingersoft.gsa.cloud.base.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.database.bean.Discount;
import com.gingersoft.gsa.cloud.database.bean.Function;
import com.gingersoft.gsa.cloud.function.FunctionManager;
import com.gingersoft.gsa.cloud.function.FunctionModule;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.print.PrinterUtils;
import com.gingersoft.gsa.cloud.table.app.GoldConstants;
import com.gingersoft.gsa.cloud.table.mvp.contract.OrderContentContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.BaseRespose;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.TableDetail;
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.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.OrderMoneyAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.OrderTopFunctionAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.DiscountDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
import com.jess.arms.base.DefaultAdapter;
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 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.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 GetTableTimer tableTimer;
    private Disposable mGetTablesDataDisposable;

    private DiscountDialog.Builder mDiscountDialog;

    @Inject
    public OrderContentPresenter(OrderContentContract.Model model, OrderContentContract.View rootView) {
        super(model, rootView);
        this.IActivity = (OrderContentActivity) rootView;

    }

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

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

    public void initItemListener() {
        mOrderTopFunctionAdapter.setOnItemClickListener(new DefaultAdapter.OnRecyclerViewItemClickListener() {

            @Override
            public void onItemClick(View view, int viewType, Object data, int position) {
                mRootView.recordOperat(true);
                if (XClickUtil.isFastDoubleClick(view, 1000)) {
                    return;
                }
                Function function = (Function) data;
                switch (function.getResName()) {
                    case "送單":
                        sendOrder(false);
                        break;
                    case "印單":
                        if (!canPrint()) {
                            return;
                        }
                        if (hasNesOrderFoods()) {
                            //有未送單食品先送單
                            sendOrder(true);
                        } else {
                            printOrder(OpenTableManage.getDefault().getTableBean().getId(), false);
                        }
                        break;
                    case "結賬":
//                        if (!canPay()) {
//                            return;
//                        }
                        mRootView.startActivityForResult(OrderContentActivity.BILL_CODE, OrderPayActivity.class, null);
                        break;
                    case "轉移":
                        if (!canTransfer()) {
                            return;
                        }
                        mRootView.showTransferFoodLayout();
                        break;
                    case "折扣":
                        if (!canDiscount()) {
                            return;
                        }
                        showDiscountDialog();
                        break;
                }
            }
        });
        mOrderMoneyAdapter.setOnItemClickListener(new OrderMoneyAdapter.OnItemClickListener() {

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

            }

            @Override
            public void onItemDeleteClick(BillOrderMoney datasBean, int position) {
                removeOrderDetailItem(position);
            }
        });
        mOrderTopFunctionAdapter.setmOnLongClickListener((v, position) -> {
            if (mFunctionList != null) {
                if (mFunctionList.get(position).getResName().equals("印單") || mFunctionList.get(position).getResName().equals("送單")) {
                    PrinterUtils.switchPrintMethod(v.getContext());
                }
            }
            return false;
        });
    }

    public void initTopFunctionData() {
        if (MyOrderManage.getInstance().isModifyOrder()) {
            //修改訂單隱藏送單，印單功能
            mFunctionList.add(new Function("結賬", Color.parseColor("#FFFFFF"), Color.parseColor("#DC0000"), 24));
        } 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));
//            List<Function> functions = FunctionManager.getDefault().getFunctionByResModule(IActivity, FunctionModule.Table.class, "order");
//            for (int i = 0; i < functions.size(); i++) {
//                functions.get(i).setTextSize(ArmsUtils.getDimens(IActivity, R.dimen.sp_14));
//                functions.get(i).setTextColor(ArmsUtils.getColor(IActivity, R.color.theme_white_color));
//                functions.get(i).setIconRes(FunctionModule.Table.order[i].getOpenIconRes());
//            }
//            mFunctionList.addAll(functions);
        }
    }

    protected void createOrder(boolean isPrint) {
        CreateOrderRequest request = getCreateOrderRequest(getOrderFoodLists());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/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<BaseResult>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            saveCreateTime(info.getSysTime());
                            if (info.getData() != null) {
                                setOrderId((Double) info.getData());
                            }
                            if (isPrint) {
                                printOrder(OpenTableManage.getDefault().getTableBean().getId(), true);
                            } else {
                                mRootView.sendSuccess();
                                mRootView.showMessage("送單成功");
                                printSendOrder(getOrderFoodLists());
                                mAppManager.killActivity(MealStandActivity.class);
                                mRootView.killMyself();
                            }
                        } else {
                            if (isPrint) {
                                printOrder(OpenTableManage.getDefault().getTableBean().getId(), true);
                            } else {
                                mRootView.showMessage("送單失敗");
                            }
                        }
                    }
                });
    }

    protected void addOrderFood(boolean isPrint) {
        List<OrderDetail> foodLists = getOrderFoodLists();
        for (OrderDetail food : foodLists) {
            food.setOrderId(MyOrderManage.getInstance().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<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            if (isPrint) {
                                printOrder(OpenTableManage.getDefault().getTableBean().getId(), true);
                            } else {
                                mRootView.showMessage("送單成功");
                                printSendOrder(foodLists);
                            }
                        } else {
                            if (isPrint) {
                                printOrder(OpenTableManage.getDefault().getTableBean().getId(), true);
                            } else {
                                //TODO 未新增食品點擊送單 後台不讓過直接提示即可，不調用打印
                                if (!hasNesOrderFoods()) {
                                    //TODO 未新增食品點擊送單 後台不讓過直接提示即可
                                    mRootView.showMessage("送單成功");
//                                    mRootView.sendSuccess();
                                } else {
                                    mRootView.showMessage("送單失敗");
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 送單
     */
    private void printSendOrder(List<OrderDetail> newFoods) {
        MyOrderManage.getInstance().setNewFoodList(newFoods);
        CC.obtainBuilder("Component.Print")
                .setActionName("printActivity")
                .addParam("type", 3)
                .build()
                .callAsyncCallbackOnMainThread((cc, result) -> {
                    Log.e("error", "是否成功打印：" + result.isSuccess());
//                    if (result.isSuccess()) {
//                        //打印成功
//
//                    }
                    mRootView.sendSuccess();
                });
          //打印上菜紙
//        CC.obtainBuilder("Component.Print")
//                .setActionName("printActivity")
//                .addParam("NewFoods", newFoods)
//                .addParam("type", 0)
//                .build()
//                .callAsyncCallbackOnMainThread((cc, result) -> {
//                    if (result.isSuccess()) {
//                        //打印成功
//                        mRootView.killMyself();
//                    }
//                });
    }

    public void printOrder(int tableId, boolean isSend) {
        RequestBody requestBody = new FormBody.Builder()
                .add("tableId", tableId + "")
                .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<BaseRespose>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseRespose info) {
                        if (info != null && info.isSuccess()) {
                            CC.obtainBuilder("Component.Print")
                                    .addParam("type", 1)//印單
                                    .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(MyOrderManage.getInstance().getOrderId());
                            }
                        }
                    }
                });
    }


    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<BaseRespose>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseRespose info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null && info.getData().getOrderDetails() != null) {
                                OpenTableManage.getDefault().setPeopleNumber(info.getData().getPerson());
                                //緩存訂單信息
                                MyOrderManage.getInstance().setOrderBean(new OrderBean(info.getData()));
                                //緩存食品信息
                                List<OrderDetail> orderDetailList = OrderAssemblyUtil.assemblyOrder(OrderDetail.orderTransOrderDetails(info.getData().getOrderDetails()));
                                mOrderFoodList.clear();
                                mOrderFoodList.addAll(orderDetailList);
                            }
                            mSelectMealAdapter.notifyDataSetChanged();
                            mSelectMealAdapter.setIndex();
                        } else {
                        }
                    }
                });
    }

    public void getTables(boolean show, RefreshLayout refreshLayout) {
        int restaurantId = GsaCloudApplication.getRestaurantId(mApplication);
        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(int tableId, TextView tv_table_name) {
        mModel.getTable(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<TableDetail>(mErrorHandler) {

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

    private void transferFood(TableBean.DataBean dataBean) {

        String orderDetailsIds = getSelectFoodIds();

        long orderId = MyOrderManage.getInstance().getOrderId();

        RequestBody requestBody = new FormBody.Builder()
                .add("id", String.valueOf(dataBean.getId()))
                .add("orderId", String.valueOf(orderId))
                .add("orderDetailsIds", orderDetailsIds)
                .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<BaseRespose>(mErrorHandler) {

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

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

                        if (info.isSuccess()) {

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

                            if (info.getData() != null && info.getData().getOrderDetails() != null) {

                                //緩存訂單信息
                                MyOrderManage.getInstance().setOrderBean(new OrderBean(info.getData()));
                                //緩存食品信息
                                List<OrderDetail> orderDetailList = OrderAssemblyUtil.assemblyOrder(OrderDetail.orderTransOrderDetails(info.getData().getOrderDetails()));

                                mOrderFoodList.clear();
                                mOrderFoodList.addAll(orderDetailList);
                            }

                            mSelectMealAdapter.notifyDataSetChanged();
                            mSelectMealAdapter.setIndex();

                            IActivity.initOrderDetail();
                            IActivity.backPressed();
                        } else {
                            mRootView.showMessage("獲取訂單數據失敗");
                        }
                    }
                });
    }

    private void showDiscountDialog() {
        if (mDiscountDialog == null) {
            mDiscountDialog = new DiscountDialog.Builder(IActivity);
            mDiscountDialog.setOnClickListener(new DiscountDialog.Builder.OnClickListener() {
                @Override
                public void onItemClick(Discount item, int position) {
                    addOrderDiscount(item,0,false);
                }
            });
        }
        mDiscountDialog.addItems(mModel.queryDB_DiscountList());
//        mDiscountDialog.addItems(getDiscountList());
//        mDiscountDialog.setTopBarBagcolor(mFunctionList.get(4).getBackgroundColor());
        mDiscountDialog.build().show();
    }

//    /**
//     * 添加賬單折扣
//     *
//     * @param discount
//     */
//    private void addOrderDiscount(Discount discount) {
//        double totalMoney = getFoodTotal();
//        double discountPrice = Discount.calculationDiscount(discount, totalMoney);
//        BillOrderMoney orderMoney = new BillOrderMoney();
//        orderMoney.setMoney(discountPrice);
//        orderMoney.setTitle(discount.getRemark());
//        orderMoney.setType(BillOrderMoney.DISCOUNT_TYPE);
//        orderMoney.setDiscount(discount);
//        mOrderMoneyList.add(orderMoney);
//        mOrderMoneyAdapter.notifyDataSetChanged();
//        //更新總金額
//        IActivity.initOrderDetail();
//    }

    public void removeOrderDetailItem(int index) {
        if (index < mOrderMoneyList.size()) {
            mOrderMoneyList.remove(index);
            mOrderMoneyAdapter.notifyDataSetChanged();
            //更新總金額
            IActivity.initOrderDetail();
        }
    }

    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 (myOrderManage.getOrderFoodList().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 initGetTableTimer() {
        if (tableTimer == null) {
            tableTimer = new GetTableTimer(GoldConstants.refreshTime * 1000, GoldConstants.refreshTime * 1000);
        }
        TableActivity.isRefreshData = true;
    }

    public void startTableTimer() {
        initGetTableTimer();
        if (tableTimer != null) {
            tableTimer.start();
        }
    }

    public void cancelTableTimer() {
        if (tableTimer != null) {
            tableTimer.cancel();
        }
    }

    /**
     * 计时器类 定時更新餐台数据
     */
    private class GetTableTimer extends CountDownTimer {

        public GetTableTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            if (IActivity.isRefreshData()) {
                getTables(false, null);
            }
            this.start();
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
        }
    }

    public Disposable getGetTablesDataDisposable() {
        return mGetTablesDataDisposable;
    }

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