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

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

import com.billy.cc.core.component.CC;
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.MemberInfo;
import com.gingersoft.gsa.cloud.base.order.bean.OrderBean;
import com.gingersoft.gsa.cloud.base.order.billItem.BillItem;
import com.gingersoft.gsa.cloud.base.order.billItem.DiscountItem;
import com.gingersoft.gsa.cloud.base.order.commodity.OrderDetail;
import com.gingersoft.gsa.cloud.base.order.bean.discount.CouponDiscountBean;
import com.gingersoft.gsa.cloud.base.order.bean.discount.CouponDiscountResult;
import com.gingersoft.gsa.cloud.base.order.discount.NomalDiscount;
import com.gingersoft.gsa.cloud.base.order.order.BaseOrder;
import com.gingersoft.gsa.cloud.base.order.order.DoshokuOrder;
import com.gingersoft.gsa.cloud.base.table.bean.TableBean;
import com.gingersoft.gsa.cloud.base.table.bean.TableExtBean;
import com.gingersoft.gsa.cloud.base.utils.JsonUtils;
import com.gingersoft.gsa.cloud.base.utils.RestaurantExpandInfoUtils;
import com.gingersoft.gsa.cloud.base.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.constans.ExpandConstant;
import com.gingersoft.gsa.cloud.constans.FoodSummaryConstans;
import com.gingersoft.gsa.cloud.constans.GoldConstants;
import com.gingersoft.gsa.cloud.constans.PrintConstans;
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.print.PrinterUtils;
import com.gingersoft.gsa.cloud.table.ComponentTable;
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.BaseOrderRespose;
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.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 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 SplitTableDialog mSplitTableDialog;
    private DiscountDialog.Builder mDiscountDialog;
    /**
     * 整單折扣邏輯
     */
    private BillDiscountAction mNomalDiscountAction;

    @Inject
    public OrderContentPresenter(OrderContentContract.Model model, OrderContentContract.View rootView) {
        super(model, rootView);
        this.IActivity = (OrderContentActivity) rootView;
        if (!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;
    }

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

        setPrinterMachineName();
    }

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

                mRootView.recordOperat(true);

                switch (function.getResName()) {
                    case "送單":
                        sendOrder(false, null);
                        break;
                    case "印單":
                        if (!canPrint()) {
                            return;
                        }
                        if (hasNesOrderFoods() || getNewDiscount() != null) {
                            //有未送單食品先送單
                            sendOrder(true, null);
                        } else {
                            printOrder(DoshokuOrder.getInstance().getOpenTableInfo().getId(), false);
                        }
                        break;
                    case "結賬":
//                        if (!canPay()) {
//                            return;
//                        }
                        if (hasNesOrderFoods() || getNewDiscount() != null || 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("ComponentDeliveryPick")
                                .setActionName("SendOrder")
                                .build()
                                .call();
                        break;
                }
            }

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

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

            }

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

    public void initTopFunctionData() {
        if (mFunctionList.size() > 0) {
            mFunctionList.clear();
        }
        if (BaseOrder.isCurrentOrderType(FoodSummaryConstans.RESTAURANT_MODE) && 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 {
            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));
            } 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));
            }
//            }
        }
    }

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

                    @Override
                    public void onNext(@NonNull BaseOrderRespose 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<BaseOrderRespose>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull BaseOrderRespose info) {
                        sendOrderRespose(info, isPrint, afterToActivity);
                    }
                });
    }

    private void sendOrderRespose(BaseOrderRespose 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);
            }
            CC.obtainBuilder("Component.Print")
                    .setActionName("printActivity")
                    .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_SERVE)
                    .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<BaseOrderRespose>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseOrderRespose info) {
                        if (info != null && info.isSuccess()) {
                            if (RestaurantExpandInfoUtils.getValue(ExpandConstant.MergeSendFood, true)) {
                                //合并主食品
                                mergeMainFoodNumber(mOrderMealList);
                            }
                            CC.obtainBuilder("Component.Print")
                                    .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_SLIP)//印單
                                    .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) {
                                CouponDiscountResult couponResult = JsonUtils.parseObject(info.getData(), CouponDiscountResult.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(CouponDiscountResult.ERROR_CODE_0001)) {
                                mRootView.showMessage("會員已在其他餐廳使用");
                            } else if (info.getErrCode().equals(CouponDiscountResult.ERROR_CODE_0002)) {
                                mRootView.showMessage("請掃描當前品牌的優惠券碼");
                            } else if (info.getErrCode().equals(CouponDiscountResult.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<BaseOrderRespose>(mErrorHandler) {

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

    public void getTables(boolean show, RefreshLayout refreshLayout) {
        int restaurantId = GsaCloudApplication.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<TableDetail>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull TableDetail result) {
                        if (result.isSuccess()) {
                            TableBean.DataBean tableBean = result.getData();
                            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<BaseOrderRespose>(mErrorHandler) {

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

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

                        if (info.isSuccess()) {

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

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


    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(BaseOrderRespose info) {
        if (info.getData() != null) {

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

                mTableInfo.setPerson(info.getData().getPerson());
                //緩存訂單信息
                mDoshokuOrder.setOrderPlaced(new OrderBean(info.getData()));
                //緩存食品信息
                List<OrderDetail> orderDetailList = OrderAssemblyUtil.assemblyOrder(OrderDetail.orderTransOrderDetails(info.getData().getOrderDetails()));

                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));
            }
            mOrderMoneyAdapter.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 removeBillItem(int index) {
        if (index < mBillItemList.size()) {
            BillItem billItem = mBillItemList.get(index);
            if (billItem instanceof DiscountItem) {
                //刪除折扣列表對應數據
                mShoppingCart.delMultyDiscount(((DiscountItem) billItem).getDiscount());
            }
            updateBillInfo();
        }
    }


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

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