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

import android.app.Application;
import android.os.CountDownTimer;
import android.text.TextUtils;
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.OrderBean;
import com.gingersoft.gsa.cloud.base.common.bean.OrderDetail;
import com.gingersoft.gsa.cloud.base.common.bean.table.TableBean;
import com.gingersoft.gsa.cloud.base.common.bean.table.TableExtBean;
import com.gingersoft.gsa.cloud.base.common.bean.mealManger.MyOrderManage;
import com.gingersoft.gsa.cloud.base.common.bean.mealManger.OpenTableManage;
import com.gingersoft.gsa.cloud.base.utils.JsonUtils;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.constans.GoldConstants;
import com.gingersoft.gsa.cloud.constans.PrintConstans;
import com.gingersoft.gsa.cloud.database.bean.Food;
import com.gingersoft.gsa.cloud.database.bean.FoodCombo;
import com.gingersoft.gsa.cloud.database.bean.Function;
import com.gingersoft.gsa.cloud.database.bean.Modifier;
import com.gingersoft.gsa.cloud.database.utils.FoodComboDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.ModifierDaoUtils;
import com.gingersoft.gsa.cloud.function.FunctionManager;
import com.gingersoft.gsa.cloud.table.ComponentTable;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.app.TableOperatTypeConstant;
import com.gingersoft.gsa.cloud.table.mvp.contract.TableContract;
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.utils.OrderAssemblyUtil;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.TableActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.BottomFunctionAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.SplitTableDialog;
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.mvp.BasePresenter;
import com.jess.arms.utils.RxLifecycleUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
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.RequestBody;

import static com.gingersoft.gsa.cloud.base.common.bean.OrderDetail.FOOD_TYPE;
import static com.gingersoft.gsa.cloud.base.common.bean.OrderDetail.MODIFIER_TYPE;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 12/27/2019 19:19
 * <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 TablePresenter extends BasePresenter<TableContract.Model, TableContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private TableActivity IActivity;

    private List<TableBean.DataBean> mTableList = new ArrayList<>();

    private BottomFunctionAdapter mBottomFunctionAdapter;
    private List<Function> mBottomFunctionList = new ArrayList<>();

    //定时获取餐台 定时器
    private GetTableTimer tableTimer;
    private Disposable mGetTablesDataDisposable;

    /**
     * 当前选择的操作：
     * 1#分台
     * 2#上菜纸
     * 3#重置
     * 4#转台
     * 5#sky_order
     * 6#結賬、
     * 10#餐檯模式
     */
    private int mCurrentOperatType = -1;
    /**
     * 选中操作的台名、id、分檯編號
     */
    private String originalTableName = "";
    private long originalTableId;
    private String originalTableNumber = "";
    /**
     * 转台需要转到台名、id、分檯編號
     */
    private String targetTableName = "";
    private long targetTableId;
    private String targetTableNumber = "";

    @Inject
    public TablePresenter(TableContract.Model model, TableContract.View rootView) {
        super(model, rootView);
        this.IActivity = (TableActivity) rootView;

        initGetTableTimer();
    }

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

        cancelTableTimer();
    }

    public void initBottomFunction() {
        if (mBottomFunctionAdapter == null) {
            mBottomFunctionAdapter = new BottomFunctionAdapter(IActivity, mBottomFunctionList);
            mRootView.setBottomFunctionAdapter(mBottomFunctionAdapter);
        }
        initBottomFunctionItem();
        initBottomFunctionListener();
    }

    private void initBottomFunctionListener() {
        mBottomFunctionAdapter.setOnItemClickListener(new DefaultAdapter.OnRecyclerViewItemClickListener() {

            @Override
            public void onItemClick(View view, int viewType, Object data, int position) {
//                Function function = (Function) data;
//                switch (function.getStatus()) {
//                    case STATUS_NONACTIVATED:
//                        mRootView.showMessage("服務暫未開通,敬請期待");
//                        return;
//                    case STATUS_TIME_LIMIT:
//                        mRootView.showMessage("服務已到期,請前往續費");
//                        return;
//                }
//                if (function.getResUrl().equals(ComponentTable.table.bottom[0].getKeyRes())) {
//                    //重置
//                    mRootView.setCurrentOperatType(TableOperatTypeConstant.init_table_3);
//                } else if (function.getResUrl().equals(ComponentTable.table.bottom[1].getKeyRes())) {
//                    //轉檯
//                    mRootView.setCurrentOperatType(TableOperatTypeConstant.move_table_4);
//                } else if (function.getResUrl().equals(ComponentTable.table.bottom[3].getKeyRes())) {
//                    //上菜紙
//                    mRootView.setCurrentOperatType(TableOperatTypeConstant.print_parper_2);
//                }
                switch (position) {
                    case 0:
                        //重置
                        mRootView.setCurrentOperatType(TableOperatTypeConstant.init_table_3);
                        break;
                    case 1:
                        //轉檯
                        mRootView.setCurrentOperatType(TableOperatTypeConstant.move_table_4);
                        break;
                    case 2:
                        //分檯
                        mRootView.setCurrentOperatType(TableOperatTypeConstant.splite_table_1);
                        break;
                    case 3:
                        //上菜紙
                        mRootView.setCurrentOperatType(TableOperatTypeConstant.print_parper_2);
                        break;
                }
            }
        });
    }

    public void initBottomFunctionItem() {
        boolean addFuctions = false;
        List<Function> functions = FunctionManager.getDefault().getFunctionByResModule(GsaCloudApplication.getAppContext(), ComponentTable.table.class, ComponentTable.table.bottom, "bottom");
        for (int i = 0; i < functions.size(); i++) {
            if (functions.get(i).getParentId() == 0) {
                //有配置餐檯操作模块
                functions.remove(i);
                addFuctions = true;
            }
        }
        if (mBottomFunctionList.size() > 0) {
            mBottomFunctionList.clear();
        }
        if (addFuctions) {
            mBottomFunctionList.addAll(functions);
            mRootView.setBottomFunctionVisibility(true);
            mBottomFunctionAdapter.notifyDataSetChanged();
        } else {
            mRootView.setBottomFunctionVisibility(false);
        }
//        mBottomFunctionList.add(new Function((long) 1, "重置檯號", ArmsUtils.getColor(IActivity, R.color.theme_black), ArmsUtils.getDimens(IActivity, R.dimen.sp_14), R.mipmap.table_init));
//        mBottomFunctionList.add(new Function((long) 2, "轉檯", ArmsUtils.getColor(IActivity, R.color.theme_black), ArmsUtils.getDimens(IActivity, R.dimen.sp_14), R.mipmap.table_move));
//        mBottomFunctionList.add(new Function((long) 3, "分檯", ArmsUtils.getColor(IActivity, R.color.theme_black), ArmsUtils.getDimens(IActivity, R.dimen.sp_14), R.mipmap.table_splite));
//        mBottomFunctionList.add(new Function((long) 4, "skyorder", ArmsUtils.getColor(IActivity, R.color.theme_black), ArmsUtils.getDimens(IActivity, R.dimen.sp_14), R.mipmap.table_skyorder));
//        mBottomFunctionList.add(new Function((long) 5, "上菜紙", ArmsUtils.getColor(IActivity, R.color.theme_black), ArmsUtils.getDimens(IActivity, R.dimen.sp_14), R.mipmap.table_paper));
    }


    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(() -> {
                    if (show && refreshLayout == null) {
                        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 (!TableActivity.isRefreshData) {
                            return;
                        }
                        if (tableBean.isSuccess()) {
                            List<TableBean.DataBean> tableBeanData = tableBean.getData();
                            if (tableBeanData != null && tableBeanData.size() > 0) {
                                if (mTableList.size() > 0) {
                                    mTableList.clear();
                                }
                                sortTableList(tableBeanData);
                                mTableList.addAll(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);
                        if (mRootView.getCurrentTableFragment() != null) {
                            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 loadOrderToPrint(long tableId, Long orderId) {
        if (orderId == null)
            return;
        mModel.getOrderById(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 respose) {
                        if (respose.isSuccess()) {
                            OpenTableManage.getDefault().setPeopleNumber(0);
                            //設置當前開台數據1584427984728 1584428017196 1584428086282
                            TableBean.DataBean dataBean = getTableById(tableId);
                            TableBean.DataBean openTableBean = null;
                            if (dataBean != null) {
                                openTableBean = new TableBean.DataBean(dataBean);
                            }
                            OrderBean orderBean = respose.getData();
                            if (orderBean != null && respose.getData().getOrderDetails() != null) {
                                if (respose.getData().getCreateTime() != null && openTableBean != null) {
                                    //將開台時間設置為訂單創建時間
                                    openTableBean.setCreateTime(TimeUtils.getFormatTime(respose.getData().getCreateTime(), TimeUtils.DEFAULT_DATE_FORMAT));
                                }
                                OpenTableManage.getDefault().setPeopleNumber(orderBean.getPerson());

                                List<OrderBean.OrderDetailsBean> orderDetailsBeans = respose.getData().getOrderDetails();

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

                                MyOrderManage.getInstance().setOrderFoodList(orderDetailList);
                            } else {
                                MyOrderManage.getInstance().setOrderBean(null);
                                MyOrderManage.getInstance().setOrderFoodList(new ArrayList<>());
                            }
                            OpenTableManage.getDefault().setTableBean(openTableBean);

                            printParper();
                        } else {
                            CommonTipDialog.showSurpisedDialog(IActivity, respose.getErrMsg(), null, null, null, null, null);
                        }
                    }

                    /**
                     * 打印上菜紙
                     */
                    private void printParper() {
                        CC.obtainBuilder("Component.Print")
                                .setActionName("printActivity")
                                .addParam(PrintConstans.PRINT_TYPE, PrintConstans.PRINT_SERVE)
                                .build()
                                .callAsyncCallbackOnMainThread((cc, result) -> {
                                    //清空賬單數據
                                    MyOrderManage.getInstance().clear();
                                    //清空開檯數據
                                    OpenTableManage.getDefault().clear();

                                    mRootView.canceOperat();
                                });
                    }
                });
    }

    public void openTable(long tableId, TableBean.DataBean tableExtBean) {
        String tableNumber = "";
        if (tableExtBean != null) {
            tableNumber = tableExtBean.getTableNumber();
        }
        RequestBody requestBody = new FormBody.Builder()
                .add("id", String.valueOf(tableId))
                .add("tableNumber", tableNumber)
                .build();
        mModel.openTable(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 respose) {
                        if (respose.isSuccess()) {
                            //設置當前開台數據
                            TableBean.DataBean openTableBean;
                            if (tableExtBean != null) {
                                openTableBean = tableExtBean;
                                if (IActivity.getSplitTableDialog() != null) {
                                    IActivity.getSplitTableDialog().closeDialog();
                                }
                            } else {
                                openTableBean = getTableById(tableId);
                            }
                            OpenTableManage.getDefault().setPeopleNumber(0);
                            OpenTableManage.getDefault().setPeopleNumber(openTableBean.getSeatCount());

                            OrderBean orderBean = respose.getData();
                            if (orderBean != null && respose.getData().getOrderDetails() != null) {
                                if (respose.getData().getCreateTime() != null && openTableBean != null) {
                                    //將開台時間設置為訂單創建時間
                                    openTableBean.setCreateTime(TimeUtils.getFormatTime(respose.getData().getCreateTime(), TimeUtils.DEFAULT_DATE_FORMAT));
                                }
                                OpenTableManage.getDefault().setPeopleNumber(orderBean.getPerson());

                                List<OrderBean.OrderDetailsBean> orderDetailsBeans = orderBean.getOrderDetails();

                                setFoodPoints(orderDetailsBeans);
                                //設置套餐topId
                                setTopId(orderDetailsBeans);
                                //緩存訂單信息
                                MyOrderManage.getInstance().setOrderBean(new OrderBean(orderBean));
                                //緩存食品信息
                                List<OrderDetail> orderDetailList = OrderAssemblyUtil.assemblyOrder(OrderDetail.orderTransOrderDetails(orderDetailsBeans));
                                MyOrderManage.getInstance().setOrderFoodList(orderDetailList);

                                if (orderBean.getMemberInfo() != null) {
                                    //设置会员信息
                                    MyOrderManage.getInstance().setMemberInfo(orderBean.getMemberInfo());
                                }
                            } else {
                                MyOrderManage.getInstance().setOrderBean(null);
                                MyOrderManage.getInstance().setOrderFoodList(new ArrayList<>());
                            }
                            OpenTableManage.getDefault().setTableBean(openTableBean);
                            mRootView.startMealStandActivity();
                        } else {
                            CommonTipDialog.showSurpisedDialog(IActivity, respose.getErrMsg(), null, null, null, null, null);
                        }
                    }
                });
    }

    /**
     * 設置已送單食品積分(訂單表沒有存儲食品積分字段)
     */
    private void setFoodPoints(List<OrderBean.OrderDetailsBean> orderDetailsBeans) {
        List<Food> foods = mModel.queryDB_AllFoodList();
        for (int i = 0; i < orderDetailsBeans.size(); i++) {
            OrderBean.OrderDetailsBean orderDetailsBean = orderDetailsBeans.get(i);
            if (orderDetailsBean.getType() != FOOD_TYPE) {
                continue;
            }
            for (int j = 0; j < foods.size(); j++) {
                Food food = foods.get(j);
                if (food.getId() == orderDetailsBean.getProductId()) {
                    orderDetailsBean.setPointsAdd(food.getPointsAdd());
                    orderDetailsBean.setPointsRedeem(food.getPointsRedeem());
                }
            }
        }
    }

    /**
     * 設置套餐，細項組別ID
     *
     * @param orderDetailsBeans
     */
    private void setTopId(List<OrderBean.OrderDetailsBean> orderDetailsBeans) {
        long paroductId = 0;
        long topId = 0;
        for (int i = 0; i < orderDetailsBeans.size(); i++) {
            OrderBean.OrderDetailsBean orderDetailsBean = orderDetailsBeans.get(i);
            if (orderDetailsBean.getType() == FOOD_TYPE) {
                int nextIndex = i + 1;
                if (orderDetailsBean.getParentId() == 0 || (orderDetailsBeans.size() > nextIndex && orderDetailsBeans.get(nextIndex).getType() == MODIFIER_TYPE)) {
                    paroductId = orderDetailsBean.getProductId();
                }
                topId = getComboIdByFid(paroductId);
            } else {
                topId = 0;
                List<Modifier> modifierList = mModel.queryDB_ModifierList(paroductId, ModifierDaoUtils.modifierMode_All);
                for (Modifier modifier : modifierList) {
                    if (modifier.getMid() == orderDetailsBean.getProductId()) {
                        topId = modifier.getTopId();
                        break;
                    }
                }
//                topId = CommonConfiguration.getInstance().getModifierTopIdMid((int) orderDetailsBean.getProductId());
            }
            if (orderDetailsBean.getParentId() != 0) {
                orderDetailsBean.setTopId(topId);
            }
        }
    }

    private long getComboIdByFid(long fid) {
        FoodComboDaoUtils daoUtils = new FoodComboDaoUtils(GsaCloudApplication.getAppContext());
        List<FoodCombo> foodCombos = daoUtils.queryCombosByQueryBuilder(fid);
        if (foodCombos != null && foodCombos.size() > 0) {
            return foodCombos.get(0).getComId();
        }
        return 0;
    }

    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 (!TextUtils.isEmpty(tableBean.getTableNumber())) {
                                    //如果是分檯拼接分檯名称
                                    tableBean.setTableName(tableBean.getTableName() + "-" + tableBean.getTableNumber());
                                }
                                if (originalTableId == 0) {
                                    if (tableBean.getUseStatus() == 1) {
                                        mRootView.showMessage("此檯使用中.");
                                        return;
                                    }
                                    if (tableBean.getStatus() == 0) {
                                        mRootView.showMessage("此檯未開檯.");
                                        return;
                                    }
                                    originalTableName = tableBean.getTableName();
                                    originalTableId = tableBean.getId();
                                    originalTableNumber = tableBean.getTableNumber();
                                    mRootView.setOperatContentText("由: " + originalTableName + " 轉到 ");
                                } else {
                                    if (tableBean.getUseStatus() == 1) {
                                        mRootView.showMessage("此檯使用中.");
                                        return;
                                    }
                                    targetTableName = tableBean.getTableName();
                                    targetTableId = tableBean.getId();
                                    targetTableNumber = tableBean.getTableNumber();
                                    if (tableBean.getStatus() == 1 || tableBean.getStatus() == 2 || tableBean.getStatus() == 3) {
                                        mRootView.setOperatContentText("由: " + originalTableName + " 合併 " + targetTableName);
                                    } else {
                                        mRootView.setOperatContentText("由: " + originalTableName + " 轉到 " + targetTableName);
                                    }
                                    showOperatTipDialog(tableBean);
                                }
                            }
                        } else {
                            mRootView.showMessage(result.getErrMsg());
                        }
                    }
                });
    }

    public void turnTable(long originalTableId, long targetTableId, String tableNumber, String targetTableNumber, boolean isMergeTable) {

        RequestBody requestBody = new FormBody.Builder()
                .add("id", String.valueOf(originalTableId))
                .add("tableId", String.valueOf(targetTableId))
                .add("tableNumber", tableNumber)
                .add("targetTableNumber", targetTableNumber)
                .build();

        mModel.turnTable(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 respose) {
                        if (respose.isSuccess()) {
                            if (isMergeTable) {
                                mRootView.showMessage("合併成功");
                            } else {
                                mRootView.showMessage("轉檯成功");
                            }
                            mRootView.canceOperat();
                            //立即獲取餐檯數據
                            getTables(false, null);
                        } else {
                            mRootView.showMessage(respose.getErrMsg());
                        }
                    }
                });
    }

    public void initTable(int tableId, String tableNumber, boolean showMessage) {

        RequestBody requestBody = new FormBody.Builder()
                .add("id", tableId + "")
                .add("tableNumber", tableNumber)
                .build();

        mModel.initTable(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    if (showMessage) {
                        mRootView.showLoading(null);
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> {
                    if (showMessage)
                        mRootView.hideLoading();
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseOrderRespose>(mErrorHandler) {

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

                        if (respose.isSuccess()) {

//                            if (showMessage)
//                                mRootView.showMessage("重置成功!");

                            mRootView.canceOperat();

                            getTables(false, null);

                            refreshSplitTablesDialog();
                        } else {
                            if (showMessage)
                                mRootView.showMessage(respose.getErrMsg());
                        }
                    }
                });
    }

    public void getSplitTables(int tableId) {
        SplitTableDialog splitTableDialog = IActivity.getSplitTableDialog();
        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);
                        splitTableDialog.clearItems();
                        splitTableDialog.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());

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

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        splitTableDialog.setProgressVisibility(false);
                        splitTableDialog.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 splitTable(TableBean.DataBean tableBean) {
        mModel.splitTable(tableBean.getId())
                .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()) {
                            if (result.getData() != null) {
                                TableExtBean.DataBean tableExtBean = JsonUtils.parseObject(result.getData(), TableExtBean.DataBean.class);
                                long tableExtId = tableExtBean.getId();
                                //分檯开檯
                                openTable(tableExtId, TableBean.splitTableTransformTable(tableBean, tableExtBean));
                            }
                        } else {
                            mRootView.showMessage(result.getErrMsg());
                        }
                    }
                });
    }


    public void loadOrderList(long orderId, boolean isPrintParper) {

        RequestBody requestBody = new FormBody.Builder()
                .add("orderId", orderId + "")
                .build();

        mModel.initTable(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 respose) {

                        if (respose.isSuccess()) {
                            if (isPrintParper) {
                                //打印上菜紙
                                startPrintParper();
                            }
                        } else {
                            mRootView.showMessage(respose.getErrMsg());
                        }
                    }
                });
    }

    private void startPrintParper() {


    }

    /**
     * 刷新分檯数据
     */
    private void refreshSplitTablesDialog() {
        SplitTableDialog splitTableDialog = IActivity.getSplitTableDialog();
        if (splitTableDialog != null) {
            //刷新餐檯
            getSplitTables(splitTableDialog.getMainTableId());
        }
    }

    /**
     * 根据操作类型过滤一遍餐台
     */
    public void filterTableByOperatType() {
        if (mTableList.size() == 0) {
            return;
        }
        List<TableBean.DataBean> filterTableBeanList = new ArrayList<>();
        //如果是餐檯操作過一遍筛选
        switch (mCurrentOperatType) {
            case TableOperatTypeConstant.splite_table_1:
                for (int i = 0; i < mTableList.size(); i++) {
//                    if (mTableList.get(i).getStatus() != 0 || mTableList.get(i).getSplitStatus() == 1 ? true : false) {
                    if (mTableList.get(i).getStatus() != 0) {
                        filterTableBeanList.add(mTableList.get(i));
                    }
                }
                break;
            case TableOperatTypeConstant.print_parper_2:
                for (int i = 0; i < mTableList.size(); i++) {
                    if (mTableList.get(i).getStatus() != 0) {
                        filterTableBeanList.add(mTableList.get(i));
                    }
                }
                break;
            case TableOperatTypeConstant.init_table_3:
                for (int i = 0; i < mTableList.size(); i++) {
                    if (mTableList.get(i).getUseStatus() == 1 || mTableList.get(i).getSplitStatus() == 1) {
                        filterTableBeanList.add(mTableList.get(i));
                    }
                }
                break;
//            case TableOperatTypeConstant.skyorder_mode_5:
//                for (int i = 0; i < datasBeans.size(); i++) {
//                    mTableList.add(datasBeans.get(i));
//                }
//                break;
            case TableOperatTypeConstant.move_table_4:
            case -1: //正常餐檯模式下顯示所有餐檯數據
                filterTableBeanList.addAll(mTableList);
                break;
        }
        IActivity.nofilyFragmentUpdateTableData(filterTableBeanList);
    }

    public void showOperatTipDialog(TableBean.DataBean dataBean) {
        QMUIDialog.MessageDialogBuilder dialogBuilder = new QMUIDialog.MessageDialogBuilder(IActivity);
        dialogBuilder.setTitleIcon(R.drawable.qmui_icon_dialog_doubt);
        //是否合併檯
        boolean isMergeTable = false;
        switch (mCurrentOperatType) {
            case TableOperatTypeConstant.splite_table_1:

                break;
            case TableOperatTypeConstant.print_parper_2:
                dialogBuilder.setMessage("是否確認打印");
                break;
            case TableOperatTypeConstant.init_table_3:
                dialogBuilder.setMessage("是否確認重置" + dataBean.getTableName() + "號檯?");
                break;
            case TableOperatTypeConstant.move_table_4:
                String message;
                if (dataBean.getStatus() == 1 || dataBean.getStatus() == 2 || dataBean.getStatus() == 3) {
                    message = "是否由%s號檯合併到%s號檯";
                    isMergeTable = true;
                } else {
                    message = "是否由%s號檯轉到%s號檯";
                }
                dialogBuilder.setMessage(String.format(message, originalTableName, targetTableName));
                break;
            case TableOperatTypeConstant.skyorder_mode_5:

                break;
        }
        boolean finalIsMergeTable = isMergeTable;
        dialogBuilder.addAction(0, "確認", QMUIDialogAction.ACTION_PROP_NEGATIVE, new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                dialog.dismiss();
                switch (mCurrentOperatType) {
                    case TableOperatTypeConstant.splite_table_1:

                        break;
                    case TableOperatTypeConstant.print_parper_2:
                        loadOrderToPrint(dataBean.getId(), dataBean.getOrderId());
                        break;
                    case TableOperatTypeConstant.init_table_3:
                        initTable(dataBean.getId(), dataBean.getTableNumber(), true);
                        break;
                    case TableOperatTypeConstant.move_table_4:
                        turnTable(originalTableId, targetTableId, originalTableNumber, targetTableNumber, finalIsMergeTable);
                        break;
                    case TableOperatTypeConstant.skyorder_mode_5:

                        break;
                }
            }
        });
        dialogBuilder.addAction("取消", new QMUIDialogAction.ActionListener() {
            @Override
            public void onClick(QMUIDialog dialog, int index) {
                //重置之前選的餐檯數據
                initTableParameter();
                mRootView.setOperatTitle();
                dialog.dismiss();
            }
        });
        dialogBuilder.create(R.style.MyDialogTheme2).show();
    }

    /**
     * 初始化操作參數
     */
    public void initTableParameter() {
        originalTableName = "";
        originalTableId = 0;
        originalTableNumber = "";
        targetTableName = "";
        targetTableId = 0;
        targetTableNumber = "";
    }

    private TableBean.DataBean getTableById(long id) {
        for (int i = 0; i < mTableList.size(); i++) {
            TableBean.DataBean dataBean = mTableList.get(i);
            if (dataBean.getId() == id)
                return dataBean;
        }
        return null;
    }


    public void initGetTableTimer() {
        if (tableTimer == null) {
            tableTimer = new GetTableTimer(GoldConstants.refreshTime * 1000, GoldConstants.refreshTime * 1000);
        }
        TableActivity.isRefreshData = true;
        tableTimer.start();
    }

    public void startTableTimer() {
        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 (TableActivity.isRefreshData) {
                getTables(false, null);
            }
            this.start();
        }

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

    public Disposable getGetTablesDataDisposable() {
        return mGetTablesDataDisposable;
    }

    public int getCurrentChooseOperatType() {
        return mCurrentOperatType;
    }

    public void setCurrentChooseOperatType(int mCurrentOperatType) {
        this.mCurrentOperatType = mCurrentOperatType;
    }

    public String getOriginalTableName() {
        return originalTableName;
    }

    public void setOriginalTableName(String originalTableName) {
        this.originalTableName = originalTableName;
    }

    public long getOriginalTableId() {
        return originalTableId;
    }

    public void setOriginalTableId(int originalTableId) {
        this.originalTableId = originalTableId;
    }

    public String getTargetTableName() {
        return targetTableName;
    }

    public void setTargetTableName(String targetTableName) {
        this.targetTableName = targetTableName;
    }

    public long getTargetTableId() {
        return targetTableId;
    }

    public void setTargetTableId(int targetTableId) {
        this.targetTableId = targetTableId;
    }

    public List<TableBean.DataBean> getTableList() {
        return mTableList;
    }
}
