package com.gingersoft.gsa.cloud.table.mvp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.gingersoft.gsa.cloud.app.GsaCloudApplication;
import com.gingersoft.gsa.cloud.common.constans.FoodSummaryConstans;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.core.table.TableBean;
import com.gingersoft.gsa.cloud.common.core.user.UserContext;
import com.gingersoft.gsa.cloud.common.scan.ScanHelper;
import com.gingersoft.gsa.cloud.common.utils.VibratorUtils;
import com.gingersoft.gsa.cloud.common.utils.encryption.DESUtil;
import com.gingersoft.gsa.cloud.common.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.order.order.BaseOrder;
import com.gingersoft.gsa.cloud.order.order.DoshokuOrder;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.table.di.component.DaggerOrderContentComponent;
import com.gingersoft.gsa.cloud.table.mvp.contract.OrderContentContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.event.InitTableEvent;
import com.gingersoft.gsa.cloud.table.mvp.model.constant.OrderConentActionConstant;
import com.gingersoft.gsa.cloud.table.mvp.model.constant.TableActionConstant;
import com.gingersoft.gsa.cloud.table.mvp.presenter.OrderContentPresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.RegionTableFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.InputTableFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.ChooseNumberDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.gyf.immersionbar.ImmersionBar;
import com.jess.arms.base.BaseFragmentActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.qmuiteam.qmui.arch.QMUIFragmentPagerAdapter;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;
import com.qmuiteam.qmui.widget.tab.QMUITab;
import com.qmuiteam.qmui.widget.tab.QMUITabBuilder;
import com.qmuiteam.qmui.widget.tab.QMUITabIndicator;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment;
import com.qmuiteam.qmui.widget.tab.QMUITabView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.gingersoft.gsa.cloud.table.mvp.ui.activity.TableActivity.FUNCTION_ALL_TABLE;
import static com.gingersoft.gsa.cloud.table.mvp.ui.activity.TableActivity.FUNCTION_STATE_TABLE;
import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * 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>
 * ================================================
 */
public class OrderContentActivity extends BaseFragmentActivity<OrderContentPresenter> implements OrderContentContract.View {

    @Inject
    AppManager mAppManager;

    @BindView(R2.id.ctime)
    Chronometer chronometer;

    @BindView(R2.id.btn_table)
    QMUIAlphaButton btn_table;
    @BindView(R2.id.tv_action_name)
    TextView tv_action_name;

    @BindView(R2.id.tv_server_main)
    TextView tv_server_main;
    @BindView(R2.id.tv_time)
    TextView tv_time;
    @BindView(R2.id.btn_people_num)
    QMUIAlphaTextView btn_people_num;
    @BindView(R2.id.tv_order_no)
    TextView tvOrderNo;
    @BindView(R2.id.rv_top_function)
    RecyclerView rv_top_function;
    @BindView(R2.id.rv_food)
    RecyclerView rv_food;
    @BindView(R2.id.rv_order_detail)
    RecyclerView rv_order_detail;


    @BindView(R2.id.btn_order_count)
    Button btn_order_count;
    @BindView(R2.id.tv_whole)
    TextView tv_whole;
    @BindView(R2.id.tv_total)
    TextView tv_total;

    @BindView(R2.id.vs_transfer_food)
    ViewStub vs_transfer_food;

    public static final int BILL_CODE = 1002;

    private ChooseNumberDialog chooseNumberDialog;

    private TextView tv_table_name, tv_show_popup;
    private QMUITabSegment mTabSegment;
    private ViewPager mContentViewPager;

    private InputTableFragment inputTableFragment;
    private RegionTableFragment allTableFragment, stateTableFragment;
    private String[] mTabTitles = {"編號", "全部", "狀態:全部"};
    /**
     * 切換餐檯狀態下拉框
     */
    private QMUIPopup mTableStatusPopup;
    /**
     * 當前顯示頁下標
     */
    private int mCurrentPageIndex = 1;
    /**
     * 當前所顯示餐檯狀態（默認:全部）
     */
    private int mCurrentSelectTableStatus = TableActionConstant.table_status_0;
    /**
     * 当前选择的操作：
     * 1#賬單內容
     * 2#轉移
     */
    private int mCurrentOperatType = OrderConentActionConstant.order_conetnt_1;

    private boolean isRefreshData = false;

    private List<TableBean.DataBean> mTableList;

    private DoshokuOrder mDoshokuOrder;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerOrderContentComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        mDoshokuOrder = DoshokuOrder.getInstance();
        super.onCreate(savedInstanceState);
        //设置根布局颜色，当layout根布局是FrameLayout时直接使用merge标签，应用DecorView默认就是FrameLayout无需再套一层
        getWindow().getDecorView().setBackgroundColor(ArmsUtils.getColor(mContext, R.color.theme_white_color));
    }

    @Override
    public void configImmersionBar(ImmersionBar immersionBar) {
        immersionBar.fitsSystemWindows(true).statusBarColor("#0E655F").init();
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.table_activity_order_content; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        mPresenter.initTopFunctionData();
        mPresenter.initAdapter();
        mPresenter.initItemListener();
        initTopInfo();
        initOrderBill(mPresenter.getFoodTotal(), mPresenter.getTotalAmount());
        if (BaseOrder.isTableToMeal() && !DoshokuOrder.getInstance().isModifyOrder()) {
            //根据倒计时时间自动退出当前页面
            initAutoQuit();
        }
    }

    public void initOrderBill(double wholeAmount, double totalAmount) {
        int foodCount = mPresenter.getFoodCount();
        if (foodCount > 0) {
            btn_order_count.setText(String.valueOf(foodCount));
            btn_order_count.setVisibility(View.VISIBLE);
        } else {
            btn_order_count.setVisibility(View.INVISIBLE);
        }
        tv_whole.setText("合計  $" + wholeAmount);
        tv_total.setText("$" + totalAmount);
    }

    private void initTopInfo() {
        if (BaseOrder.isCurrentOrderType(FoodSummaryConstans.TAKEAWAY_TYPE)) {
            btn_table.setText("外賣");
            btn_people_num.setText(String.format(getString(R.string.meal_numberman_colon), 1));
            tv_time.setText("時間:" + TimeUtils.getCurrentDate(TimeUtils.DATE_FORMAT_DATE_HM));
            tv_server_main.setText("");
            tvOrderNo.setVisibility(View.GONE);
        } else {
            TableBean.DataBean tableInfo = mDoshokuOrder.getOpenTableInfo();
            Date dd = mDoshokuOrder.getOpenTableTime();
            String openTime = String.format("%tH:%tM", dd, dd);
            String tableno;
            if (tableInfo.getSplitStatus() != 0) {
                tableno = tableInfo.getTableName().trim() + "-" + tableInfo.getTableNumber().trim();
            } else {
                tableno = tableInfo.getTableName();
            }
            btn_table.setText(tableno);
            tvOrderNo.setText(String.format(getString(R.string.meal_order_number), DoshokuOrder.getInstance().getOrderNo()));
            btn_people_num.setText(String.format(getString(R.string.meal_numberman_colon), tableInfo.getPerson()));
            tv_time.setText("時間:" + openTime);
            tv_server_main.setText(UserContext.newInstance().getMemberName());
        }
    }

    private void useMember() {
        btn_table.setBackgroundResource(R.color.pink_300);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mDoshokuOrder.getMemberInfo() != null) {
            useMember();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //停止刷新餐檯數據
        onPauseRefreshTableData();
    }

    @OnClick({R2.id.btn_table, R2.id.btn_people_num})
    public void onClick(View v) {
        recordOperat(true);
        int id = v.getId();
        if (id == R.id.btn_table) {
            backPressed();
        } else if (id == R.id.btn_people_num) {
            showChoosePeopleNumDialog(true);
        }
    }

    public void backPressed() {
        switch (mCurrentOperatType) {
            case OrderConentActionConstant.transfer_food_2:
                hideTransferFoodLayout();
                break;
            default:
                killMyself();
                break;
        }
        mCurrentOperatType = OrderConentActionConstant.order_conetnt_1;
        tv_action_name.setVisibility(View.GONE);
    }

    @Override
    public void onBackPressedSupport() {
        super.onBackPressedSupport();
        if (mCurrentOperatType == OrderConentActionConstant.transfer_food_2) {
            hideTransferFoodLayout();
            mCurrentOperatType = OrderConentActionConstant.order_conetnt_1;
            tv_action_name.setVisibility(View.GONE);
        }
    }

    @Override
    public void initIntent() {

    }

    @Override
    public void initTopBar() {

    }

    @Override
    public void initLanguage() {

    }

    @Override
    public void initLayoutParams() {

    }

    @Override
    public void initLayoutVisible() {

    }

    @Override
    public void showLoading(String message) {
        if (message != null) {
            LoadingDialog.showDialogForLoading(this, message, true);
        } else {
            LoadingDialog.showDialogForLoading(this);
        }
    }

    @Override
    public void hideLoading() {
        LoadingDialog.cancelDialogForLoading();
    }

    @Override
    public void returnTableList(List<TableBean.DataBean> dataBeanList) {
        if (dataBeanList != null && dataBeanList.size() > 0) {
            mTableList = dataBeanList;
            nofilyFragmentUpdateTableData(dataBeanList);
        }
    }

    @Override
    public RegionTableFragment getCurrentTableFragment() {
        switch (mCurrentPageIndex) {
            case FUNCTION_STATE_TABLE:
                return stateTableFragment;
            default:
                return allTableFragment;
        }
    }

    @Override
    public void clickTableItem(TableBean.DataBean dataBean) {
        if (!mPresenter.transferFoodConditionFilter(dataBean.getMemberId())) {
            return;
        }
        switch (mCurrentOperatType) {
            case OrderConentActionConstant.transfer_food_2:
                if (dataBean.getSplitStatus() == 1) {
                    mPresenter.showSplitTableDialog(dataBean.getId());
                } else {
                    //獲取餐檯狀態
                    mPresenter.getTable(dataBean);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onStartRefreshTableData() {
        isRefreshData = true;
        mPresenter.startTablePolling();
        getTables(false, null);
    }

    @Override
    public void onPauseRefreshTableData() {
        isRefreshData = false;
        mPresenter.stopTablePolling();
        //立刻停止獲取餐檯接口
        if (mPresenter.getGetTablesDataDisposable() != null && !mPresenter.getGetTablesDataDisposable().isDisposed()) {
            mPresenter.getGetTablesDataDisposable().dispose();
        }
    }

    @Override
    public void showTransferFoodLayout() {
        try {
            View vsContent = vs_transfer_food.inflate();
            tv_table_name = vsContent.findViewById(R.id.tv_table_name);
            tv_show_popup = vsContent.findViewById(R.id.tv_show_popup);
            mContentViewPager = vsContent.findViewById(R.id.contentViewPager);
            mTabSegment = vsContent.findViewById(R.id.tabSegment);
            initTabAndPager();
            //開始刷新餐檯數據
            onStartRefreshTableData();
        } catch (Exception e) {
            vs_transfer_food.setVisibility(View.VISIBLE);
        } finally {
            mCurrentOperatType = OrderConentActionConstant.transfer_food_2;
            tv_table_name.setHint("請選擇目標檯號");
            setActionName();
        }
    }

    @Override
    public void hideTransferFoodLayout() {
        mCurrentOperatType = OrderConentActionConstant.order_conetnt_1;
        vs_transfer_food.setVisibility(View.GONE);
    }

    @Override
    public void showChoosePeopleNumDialog(boolean isNeedCancel) {
        if (chooseNumberDialog == null) {
            chooseNumberDialog = new ChooseNumberDialog(this);
            chooseNumberDialog.builder();
            chooseNumberDialog.setValueHint("請輸入人數");
            if (!isNeedCancel)
                chooseNumberDialog.setOnBackClickListener(new ChooseNumberDialog.OnBackClickListener() {

                    @Override
                    public void OnBackClick() {
                        recordOperat(true);
                    }
                });
            chooseNumberDialog.setOnClickListener(new ChooseNumberDialog.OnClickListener() {

                @Override
                public void onComfirmClick(String number) {
                    recordOperat(true);
                    //选择的人数大于0
//                    if (Integer.parseInt(number) > 0) {
//                    }
                    mPresenter.updateOrderPerson(number, btn_people_num);
                }

                @Override
                public void onBackPage() {
                    killMyself();
                }
            });
            chooseNumberDialog.setCancelable(isNeedCancel);
        }
        chooseNumberDialog.show();
    }

    private void initAutoQuit() {
        if (chronometer != null) {
            chronometer.setBase(SystemClock.elapsedRealtime());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
                chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {

                    @Override
                    public void onChronometerTick(Chronometer chronometer) {
                        // 执行一下看看是否按下了home键的线程
                        // 如果开始计时到现在超过了autoQuitTime秒
                        int autoQuitTime = GsaCloudApplication.functionConfiguration.getAutoQuitTimeVaule();
                        if (SystemClock.elapsedRealtime() - chronometer.getBase() > autoQuitTime * 1000) {
                            // 停止计时
                            chronometer.stop();
                            returnTableActivity(true);
                        }
                    }
                });
            }
            //开启倒计时
            chronometer.start();
        }
    }

    @Override
    public void recordOperat(boolean isPressButtonSound) {
        if (isPressButtonSound) {
            VibratorUtils.pressButtonSound(this);
        }
        //关闭倒计时
        if (chronometer != null) {
            chronometer.stop();
        }
        //重新开启倒计时
        if (chronometer != null) {
            chronometer.setBase(SystemClock.elapsedRealtime());
            chronometer.start();
        }
    }

    public void returnTableActivity(boolean initTable) {
        TableBean.DataBean tableInfo = DoshokuOrder.getInstance().getOpenTableInfo();
        if (initTable && tableInfo != null && !mDoshokuOrder.isModifyOrder()) {
            //通知更新餐台状态
            EventBus.getDefault().post(new InitTableEvent(tableInfo.getId(), tableInfo.getTableNumber()), "initTable_status_event");
        }
        mAppManager.killActivity(MealStandActivity.class);
        killMyself();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(OrderContentActivity.this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void setTopFunctionAdapter(DefaultAdapter adapter) {
        rv_top_function.setAdapter(adapter);
        setTopFunctionRecycleLayoutManager();
    }

    @Override
    public void setFoodAdapter(DefaultAdapter adapter) {
        rv_food.setAdapter(adapter);
    }

    @Override
    public void setOrderDetailAdapter(DefaultAdapter adapter) {
        rv_order_detail.setAdapter(adapter);
    }

    @Override
    public void setTopFunctionRecycleLayoutManager() {
        GridLayoutManager funtionRecycleLayoutManager = new GridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        rv_top_function.setLayoutManager(funtionRecycleLayoutManager);
        rv_top_function.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    public void setFoodRecycleLayoutManager(int orientation) {

    }

    @Override
    public void setTopFunctionRecycleSpanCount(int size) {

    }

    @Override
    public void setFoodRecycleSpanCount(int size) {

    }

    @Override
    public void printSuccess() {
        TableBean.DataBean tableInfo = DoshokuOrder.getInstance().getOpenTableInfo();
        // 设置返回码和返回携带的数据
        if (tableInfo != null) {
            //通知更新餐台状态
            EventBus.getDefault().post(new InitTableEvent(tableInfo.getId(), tableInfo.getTableNumber()), "initTable_status_event");
        }
        setResult(Activity.RESULT_OK, null);
        killMyself();
    }

    @Override
    public void sendSuccess() {
        TableBean.DataBean tableInfo = DoshokuOrder.getInstance().getOpenTableInfo();
        if (tableInfo != null) {
            //通知更新餐台状态
            EventBus.getDefault().post(new InitTableEvent(tableInfo.getId(), tableInfo.getTableNumber()), "initTable_status_event");
        }
        setResult(Activity.RESULT_OK, null);
        killMyself();
    }

    @Override
    public void setTransferTableName(String tableName) {
        tv_table_name.setText(tableName + "號檯操作中");
    }

    @Override
    public void startActivityForResult(int Code, Class clazz, Intent intent) {
        if (intent == null) {
            intent = new Intent(mContext, clazz);
        }
        startActivityForResult(intent, Code);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == BILL_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                setResult(Activity.RESULT_OK, null);
                killMyself();
            }
        } else if (requestCode == ScanHelper.CALL_BACK_QR_RESULT) {

            mPresenter.closeDiscountDialog();

            String qrCodeResult = data.getStringExtra("qrCodeResult");
            try {
                String encryptQRCode = DESUtil.decryptDES(qrCodeResult, DESUtil.KEY);
                if (!TextUtils.isEmpty(encryptQRCode)) {
                    String qrCodeContent[] = encryptQRCode.split("/");
                    if (qrCodeContent.length == 2) {
                        long couponMemberId = Long.parseLong(qrCodeContent[0]);
                        Long memberId = null;
                        if (mDoshokuOrder.getMemberInfo() != null) {
                            memberId = mDoshokuOrder.getMemberInfo().getId();
                            if (memberId != couponMemberId) {
                                showMessage("請掃描當前會員的優惠券碼");
                                return;
                            }
                        }
                        mPresenter.queryCoupon(memberId, couponMemberId, qrCodeContent[1], RestaurantInfoManager.newInstance().getRestaurantId());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void getTables(boolean show, RefreshLayout refreshLayout) {
        mPresenter.getTables(show, refreshLayout);
    }

    /**
     * 根据餐台状态 过滤餐台
     */
    public void filterTableByTableStatus(int status) {
        this.mCurrentSelectTableStatus = status;
        if (mTableList != null) {
            nofilyFragmentUpdateTableData(mTableList);
        }
    }

    /**
     * 更新相應頁面餐檯數據
     *
     * @param dataBeanList
     */
    public void nofilyFragmentUpdateTableData(List<TableBean.DataBean> dataBeanList) {
        Message message = Message.obtain();
        message.what = 1;
        message.obj = dataBeanList;
        message.arg1 = mCurrentSelectTableStatus;
        if (inputTableFragment != null) {
            inputTableFragment.setData(message);
        }
        if (allTableFragment != null) {
            allTableFragment.setData(message);
        }
        if (stateTableFragment != null) {
            stateTableFragment.setData(message);
        }
    }

    private void initTabAndPager() {
        QMUIFragmentPagerAdapter pagerAdapter = new QMUIFragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment createFragment(int position) {
                Bundle bundle = new Bundle();
                switch (position) {
                    case 1:
                        if (allTableFragment != null) {
                            return allTableFragment;
                        }
                        allTableFragment = RegionTableFragment.newInstance();
                        bundle.putInt("currentPageIndex", FUNCTION_ALL_TABLE);
                        allTableFragment.setArguments(bundle);
                        return allTableFragment;
                    case 2:
                        if (stateTableFragment != null) {
                            return stateTableFragment;
                        }
                        stateTableFragment = RegionTableFragment.newInstance();
                        bundle.putInt("currentPageIndex", FUNCTION_STATE_TABLE);
                        stateTableFragment.setArguments(bundle);
                        return stateTableFragment;
                    default:
                        if (inputTableFragment != null) {
                            return inputTableFragment;
                        }
                        inputTableFragment = InputTableFragment.newInstance();
                        return inputTableFragment;
                }
            }

            @Override
            public int getCount() {
                return mTabTitles.length;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return "";
            }
        };
        QMUITabBuilder builder = mTabSegment.tabBuilder();
        QMUITab tab1 = builder
                .setText(mTabTitles[0])
                .build(mContext);
        QMUITab tab2 = builder
                .setText(mTabTitles[1])
                .build(mContext);
        QMUITab tab3 = builder
                .setNormalDrawable(ContextCompat.getDrawable(mContext, R.drawable.arrow_down_black))
                .setSelectedDrawable(ContextCompat.getDrawable(mContext, R.drawable.arrow_down_black))
                .setIconPosition(QMUITab.ICON_POSITION_RIGHT)
                .setText(mTabTitles[2])
                .build(mContext);
        mTabSegment
                .addTab(tab1)
                .addTab(tab2)
                .addTab(tab3);

        mContentViewPager.setAdapter(pagerAdapter);
        mContentViewPager.setCurrentItem(mCurrentPageIndex);
        int space = QMUIDisplayHelper.dp2px(this, 16);
        mTabSegment.setIndicator(new QMUITabIndicator(QMUIDisplayHelper.dp2px(this, 2), false, true));
        mTabSegment.setDefaultTextSize(QMUIDisplayHelper.dp2px(this, 16), QMUIDisplayHelper.dp2px(this, 16));
        mTabSegment.setPadding(space, 0, space, 0);
        mTabSegment.setupWithViewPager(mContentViewPager, false);
        mTabSegment.setOnTabClickListener(new QMUITabSegment.OnTabClickListener() {
            @Override
            public boolean onTabClick(QMUITabView tabView, int index) {
                //彈出選擇狀態彈窗
                if (mCurrentPageIndex == 2 && index == 2) {
                    showTableStatusListPopup(tv_show_popup);
                }
                mCurrentPageIndex = index;
                return false;
            }
        });
        mTabSegment.addOnTabSelectedListener(new QMUITabSegment.OnTabSelectedListener() {

            @Override
            public void onTabSelected(int index) {
                mCurrentPageIndex = index;
            }

            @Override
            public void onTabUnselected(int index) {
                //滑動過程中先 暫停刷新數據
            }

            @Override
            public void onTabReselected(int index) {
                LogUtil.d(TAG, "onTabReselected " + index);
            }

            @Override
            public void onDoubleTap(int index) {
                LogUtil.d(TAG, "onDoubleTap " + index);
            }
        });
    }

    private void showTableStatusListPopup(View view) {
        List<Map<String, Object>> lists = new ArrayList<>();
        String[] statusTextList = new String[]{
                "全部",
                "可使用",
                "已使用",
                "已開檯",
                "已印單",
        };
        int[] statusIconList = new int[]{
                R.drawable.table_shape_status_all,
                R.drawable.table_shape_status_be_usable,
                R.drawable.table_shape_status_used,
                R.drawable.table_shape_status_send,
                R.drawable.table_shape_status_print,
        };
        for (int i = 0; i < statusTextList.length; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("text", statusTextList[i]);
            map.put("image", statusIconList[i]);
            lists.add(map);
        }
        SimpleAdapter adapter = new SimpleAdapter(this, lists, R.layout.table_item_popup_select_table_status
                , new String[]{"text", "image"}
                , new int[]{R.id.tv_status, R.id.iv_status});
        mTableStatusPopup = QMUIPopups.listPopup(this, QMUIDisplayHelper.getScreenWidth(this) / 3, QMUIDisplayHelper.getScreenHeight(this), adapter, new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mTableStatusPopup.dismiss();
                mTabSegment.updateTabText(2, "狀態:" + statusTextList[position]);
                //根据选择的餐台操作状态 显示相应的台号
                filterTableByTableStatus(position);
            }
        }).dimAmount(0.6f).show(view);
    }

    private void setActionName() {
        switch (mCurrentOperatType) {
            case OrderConentActionConstant.transfer_food_2:
                tv_action_name.setVisibility(View.VISIBLE);
                tv_action_name.setText("轉移");
                tv_action_name.setBackgroundColor(mPresenter.getFunctionList().get(3).getBackgroundColor());
                break;
            default:
                tv_action_name.setVisibility(View.GONE);
                break;
        }
    }

    public boolean isRefreshData() {
        return isRefreshData;
    }

    public void setRefreshData(boolean refreshData) {
        isRefreshData = refreshData;
    }
}
