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

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.os.SystemClock;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.app.GsaCloudApplication;
import com.gingersoft.gsa.cloud.common.constans.FoodSummaryConstans;
import com.gingersoft.gsa.cloud.common.constans.GoldConstants;
import com.gingersoft.gsa.cloud.common.constans.MealConstant;
import com.gingersoft.gsa.cloud.common.core.member.MemberInfo;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.core.table.TableBean;
import com.gingersoft.gsa.cloud.common.logan.LoganManager;
import com.gingersoft.gsa.cloud.common.scan.ScanHelper;
import com.gingersoft.gsa.cloud.common.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.common.utils.VibratorUtils;
import com.gingersoft.gsa.cloud.common.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.database.bean.Food;
import com.gingersoft.gsa.cloud.order.bean.response.OrderResponse;
import com.gingersoft.gsa.cloud.order.billItem.BillItem;
import com.gingersoft.gsa.cloud.order.billItem.DiscountItem;
import com.gingersoft.gsa.cloud.order.cart.ShoppingCart;
import com.gingersoft.gsa.cloud.order.commodity.OrderDetail;
import com.gingersoft.gsa.cloud.order.discount.MemberDiscount;
import com.gingersoft.gsa.cloud.order.discount.MultyDiscount;
import com.gingersoft.gsa.cloud.order.order.BaseOrder;
import com.gingersoft.gsa.cloud.order.order.DoshokuOrder;
import com.gingersoft.gsa.cloud.print.PrinterUtils;
import com.gingersoft.gsa.cloud.table.BuildConfig;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.table.di.component.DaggerMealStandComponent;
import com.gingersoft.gsa.cloud.table.mvp.contract.MealStandContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.SoldoutCtrFood;
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.presenter.MealStandPresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.BaseFragmentAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.FoodGroupAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.SelectMealAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.FineItemAllFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.ChooseNumberDialog;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.CustomFoodDialog;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.UseMemberDialog;
import com.gingersoft.gsa.cloud.ui.recylcler.Indicator.PagerConfig;
import com.gingersoft.gsa.cloud.ui.recylcler.Indicator.PagerGridLayoutManager;
import com.gingersoft.gsa.cloud.ui.recylcler.Indicator.PagerGridSnapHelper;
import com.gingersoft.gsa.cloud.ui.recylcler.RecyclerViewNoBugLinearLayoutManager;
import com.gingersoft.gsa.cloud.ui.recylcler.decorator.DividerItemDecoration;
import com.gingersoft.gsa.cloud.ui.recylcler.decorator.GridDividerItemDecoration;
import com.gingersoft.gsa.cloud.ui.view.PagerSlidingTabStrip;
import com.gingersoft.gsa.cloud.ui.view.SearchKeyBoardView;
import com.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseFragmentActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.lxj.xpopup.util.KeyboardUtils;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import org.simple.eventbus.EventBus;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnLongClick;

import static com.gingersoft.gsa.cloud.common.utils.log.LogUtil.v;
import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 12/27/2019 19:17
 * <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 MealStandActivity extends BaseFragmentActivity<MealStandPresenter> implements MealStandContract.View, PagerGridLayoutManager.PageListener {

    private SparseArray<View> map = new SparseArray<>(10);

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

    @BindView(R2.id.rv_select_meal)
    RecyclerView rv_select_meal;

    @BindView(R2.id.ll_food_group)
    LinearLayout ll_food_group;
    @BindView(R2.id.ll_food_group_point)
    LinearLayout ll_food_group_point;
    @BindView(R2.id.rv_food_group)
    RecyclerView rv_food_group;
    @BindView(R2.id.rv_food)
    RecyclerView rv_food;
    @BindView(R2.id.rv_combo)
    RecyclerView rv_combo;
    @BindView(R2.id.rv_modifier)
    RecyclerView rv_modifier;
    @BindView(R2.id.rv_discount)
    RecyclerView rv_discount;

    @BindView(R2.id.scroll_combo)
    ScrollView scroll_combo;

    @BindView(R2.id.rl_fine_tabs)
    RelativeLayout rl_fine_tabs;
    @BindView(R2.id.tabs_fine)
    PagerSlidingTabStrip tabs_fine;
    @BindView(R2.id.pager_fine)
    ViewPager pager_fine;
    @BindView(R2.id.meal_stand_search_keyboard_view)
    SearchKeyBoardView keyView;

    @BindView(R2.id.ll_stand_oper)
    LinearLayout ll_stand_oper;
    @BindView(R2.id.tv_no_save_return)
    TextView tv_no_save_return;
//    @BindView(R2.id.tv_send_order)
//    TextView tv_send_order;

    @BindView(R2.id.fl_order_content)
    FrameLayout fl_order_content;
    @BindView(R2.id.tv_order_content)
    TextView tv_order_content;
    @BindView(R2.id.btn_order_count)
    Button btn_order_count;

    @BindView(R2.id.fl_send_order)
    FrameLayout fl_send_order;

    @BindView(R2.id.btn_send_order)
    Button btn_send_order;
//    @BindView(R2.id.btn_send_order_machine_name)
//    TextView btn_send_order_machine_name;

    @BindView(R2.id.fl_printer_order)
    FrameLayout fl_printer_order;
    @BindView(R2.id.btn_order_printer)
    Button btn_order_printer;
    @BindView(R2.id.btn_printer_machine_name)
    TextView btn_printer_machine_name;

    @BindView(R2.id.ll_meals)
    LinearLayout ll_meals;
    @BindView(R2.id.ll_meals_main)
    LinearLayout ll_meals_main;
    @BindView(R2.id.ll_mm)
    LinearLayout ll_mm;

    @BindView(R2.id.btn_table)
    Button btn_table;
    @BindView(R2.id.btn_numberman)
    Button btn_numberman;
    @BindView(R2.id.btn_fid)
    TextView btn_fid;
    //    @BindView(R2.id.btn_temporary)
//    TextView btn_temporary;
//    @BindView(R2.id.btn_meal_discount)
//    TextView btn_meal_discount;
    @BindView(R2.id.btn_meal_delete)
    TextView btn_meal_delete;
    @BindView(R2.id.btn_meal_modify_restore)
    TextView btn_meal_modify_restore;
//    @BindView(R2.id.btn_change_Language)
//    ImageButton btn_change_Language;
//    @BindView(R2.id.btn_food_merge)
//    ImageButton btn_food_merge;
//    @BindView(R2.id.btn_food_mode)
//    TextView btn_food_mode;

    @BindView(R2.id.ll_Keys)
    LinearLayout ll_Keys;
    @BindView(R2.id.btn_key1)
    Button btn_key1;
    @BindView(R2.id.btn_key2)
    Button btn_key2;
    @BindView(R2.id.btn_key3)
    Button btn_key3;
    @BindView(R2.id.btn_key4)
    Button btn_key4;
    @BindView(R2.id.btn_keys)
    ImageButton btn_keys;

    @BindView(R2.id.ll_modify)
    LinearLayout ll_modify;
    @BindView(R2.id.btn_taste)
    QMUIAlphaTextView btn_taste;
    @BindView(R2.id.btn_msg)
    QMUIAlphaTextView btn_msg;
    @BindView(R2.id.btn_anti_selection)
    QMUIAlphaTextView btn_anti_selection;
    @BindView(R2.id.btn_select_all)
    QMUIAlphaTextView btn_select_all;
    @BindView(R2.id.btn_delete)
    QMUIAlphaTextView btn_delete;
    @BindView(R2.id.btn_end)
    QMUIAlphaTextView btn_end;

    @BindView(R2.id.tv_fine_type)
    TextView tv_fine_type;


    private FragmentManager fm;
    private FineItemAllFragment modMsgFineItemFragment, modSasteFineItemFragment;

    private ChooseNumberDialog mChooseNumberDialog;
    private UseMemberDialog mUseMemberDialog;

    private MemberInfo mMemberInfo;

    /**
     * 是否初始化细项布局
     */
    private boolean initFineItemLayout = false;
    /**
     * 公共細項頁碼:0=口味;1=特別信息
     */
    private int currentFinePage = 0;

    private int mCurrentViewMode;
    private boolean isPluMode = false;

    /**
     * 是否已初始化 已送單的折扣
     */
    private boolean initSentOrderDiscount = false;

    private ImageView[] ivPoints;
    private int mPageIndex;
    private int totalPage;
    private FoodGroupAdapter mFoodGroupAdapter;
    private PagerGridLayoutManager mLayoutManager;

    private static final int FINISH = 101;
    private static final int ORDER_CONTENT_CODE = 1002;
    public static final int SCAN_REQUEST_CODE = 0x0000c0de;

    private int foodGroupRow = 2;
    private int foodGroupColumn = 6;
    private int foodColumn = 4;
    private int comboColumn = 4;
    private int modColumn = 4;
    private int discountColumn = 4;


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

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        EventBus.getDefault().registerSticky(this);
        super.onCreate(savedInstanceState);
    }

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

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

        initUIStyleConfiguration();
        initTableDetail();
        initViewMap();
        //初始化Plu模式
        setPluMode();
        mPresenter.initAdapter();
        mPresenter.initItemClickListener();
        //初始化默认食品组
        mPresenter.initMealData();
        //搜索
        keyView.setOnConfirmCallBack(inputText -> {
            if (TextUtils.isEmpty(inputText)) {
                return;
            }
            mPresenter.toFindMeal(inputText);
        });
        if (BaseOrder.isTableToMeal() && !DoshokuOrder.getInstance().isModifyOrder()) {
            //根据倒计时时间自动退出当前页面
            initAutoQuit();
        }
        mPresenter.getCurrentSoldoutFood();
    }

    private void initUIStyleConfiguration() {
        foodGroupColumn = GsaCloudApplication.uiStyleConfiguration.getFoodGroupColumnValue();
        foodGroupRow = GsaCloudApplication.uiStyleConfiguration.getFoodGroupRowValue();
        foodColumn = GsaCloudApplication.uiStyleConfiguration.getFoodColumnValue();
        comboColumn = GsaCloudApplication.uiStyleConfiguration.getComboColumnValue();
        modColumn = GsaCloudApplication.uiStyleConfiguration.getModColumnValue();
        discountColumn = GsaCloudApplication.uiStyleConfiguration.getModColumnValue();
    }

    private void initTableDetail() {
        if (BaseOrder.isCurrentOrderType(FoodSummaryConstans.TAKEAWAY_TYPE)) {
            TableBean.DataBean tableBean = new TableBean.DataBean();
            tableBean.setPerson(1);
            tableBean.setTableName("外賣");
            DoshokuOrder.getInstance().setOpenTableInfo(tableBean);
            btn_send_order.setText("送單信息");
        } else {
            boolean openTableAutoShowKeyboard = GsaCloudApplication.functionConfiguration.getOpenTableAutoShowKeyboardVaule();
            if (openTableAutoShowKeyboard && DoshokuOrder.getInstance().getOpenTableInfo().getPerson() == 0) {
                showChoosePeopleNumDialog(false);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //更新點餐信息
        mPresenter.resetSelected();
        mPresenter.updateOrderFoodNumber();
        mPresenter.updateFoodSoldoutCtrData();
        if (BaseOrder.isTableToMeal() && DoshokuOrder.getInstance().getMemberInfo() != null) {
            useMember();
        }
        initOrderDetail();
    }

    private void initOrderDetail() {
        TableBean.DataBean dataBean = DoshokuOrder.getInstance().getOpenTableInfo();
        if (dataBean != null) {
            if (TextUtils.isEmpty(dataBean.getTableNumber())) {
                btn_table.setText(dataBean.getTableName());
            } else {
                btn_table.setText(dataBean.getTableName());
            }
            btn_numberman.setText("人數:" + dataBean.getPerson() + "");
        }
    }

    public void initFoodGroupView(List<Food> foodGroupList) {

        //总的页数向上取整
        totalPage = (int) Math.ceil(foodGroupList.size() * 1.0 / (foodGroupColumn * foodGroupRow));

        int Rows = foodGroupRow;
        if (foodGroupList.size() <= foodGroupColumn) {
            Rows = 1;
        }
        if (Rows == 0) {
            Rows = 2;
        }
        mLayoutManager = new PagerGridLayoutManager(Rows, foodGroupColumn, PagerGridLayoutManager.HORIZONTAL);

        //水平分页布局管理器
        mLayoutManager.setPageListener(this);
        //设置页面变化监听器
        rv_food_group.setLayoutManager(mLayoutManager);

        // 设置滚动辅助工具
        PagerGridSnapHelper pageSnapHelper = new PagerGridSnapHelper();
        pageSnapHelper.attachToRecyclerView(rv_food_group);

        // 如果需要查看调试日志可以设置为true，一般情况忽略即可
        PagerConfig.setShowLog(true);

        // 使用原生的 Adapter 即可
        mFoodGroupAdapter = new FoodGroupAdapter(this, foodGroupList, 1);
        rv_food_group.setAdapter(mFoodGroupAdapter);
        mFoodGroupAdapter.setOnItemClickListener(new FoodGroupAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Food datasBean, int position) {
                recordOperat(true);
                if (!mPresenter.foodGroupConditionFilter(datasBean, false)) {
                    return;
                }
                datasBean.setSelected(true);

                mPresenter.setRvMealClicked(false);
                mPresenter.changedMealByParentId(datasBean.getId());
                mPresenter.updateOrderFoodNumber();
                mPresenter.updateFoodSoldoutCtrData();
            }
        });

        int foodGroupBtnHeight = GsaCloudApplication.uiStyleConfiguration.getFoodGroupBtnHeightValue();
        int mParentColHeight = foodGroupBtnHeight * Rows;

        //设置ViewPager适配器
        rv_food_group.setLayoutParams(new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                mParentColHeight));

        //添加小圆点
        ivPoints = new ImageView[totalPage];
        for (int i = 0; i < totalPage; i++) {
            //循坏加入点点图片组
            ivPoints[i] = new ImageView(this);
            if (i == 0) {
                ivPoints[i].setImageResource(R.drawable.meal_food_group_point_focuese);
            } else {
                ivPoints[i].setImageResource(R.drawable.meal_food_group_point_unfocused);
            }
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ArmsUtils.dip2px(this, 20), ArmsUtils.dip2px(this, 12));
            lp.leftMargin = ArmsUtils.dip2px(this, 5);
            ivPoints[i].setLayoutParams(lp);
            ivPoints[i].setPadding(0, 0, 0, 0);
            ll_food_group_point.addView(ivPoints[i]);
        }
        if (foodGroupList.size() > (Rows * foodGroupColumn)) {
            ll_food_group_point.setVisibility(View.VISIBLE);
        } else {
            ll_food_group_point.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean isInitFineItemLayout() {
        return initFineItemLayout;
    }

    @Override
    public int getRestaurantId() {
        return RestaurantInfoManager.newInstance().getRestaurantId();
    }

    @Override
    public void initFineItemTabBarViewPage() {
        fm = getSupportFragmentManager();
        List<Fragment> fragmentList = new ArrayList<>();
        // Fragment标签
        modSasteFineItemFragment = FineItemAllFragment.newInstance();
        modMsgFineItemFragment = FineItemAllFragment.newInstance();
        fragmentList.add(modSasteFineItemFragment);
        fragmentList.add(modMsgFineItemFragment);
//        fragmentList.add(modCommFineItemFragment);
        // tab title
        String[] tabTitles = new String[3];
        tabTitles[0] = "";
        tabTitles[1] = "";

        BaseFragmentAdapter adapter = new BaseFragmentAdapter(this, fm, fragmentList, Arrays.asList(tabTitles));
        pager_fine.setAdapter(adapter);

        //设置tag字体颜色为灰色
        DisplayMetrics dm = getResources().getDisplayMetrics();
        // 设置Tab底部选中的指示器Indicator的高度
        tabs_fine.setIndicatorHeight((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2.5f, dm));
        // 设置Tab底部选中的指示器 Indicator的颜色
//        tabs_fine.setIndicatorColor(ArmsUtils.getColor(this, R.color.theme_color));
        tabs_fine.setIndicatorColor(ArmsUtils.getColor(this, R.color.theme_white_color));
        //设置Tab标题文字的颜色
        tabs_fine.setTextColor(ArmsUtils.getColor(this, R.color.theme_text_color));
        //设置选中的Tab文字的颜色
        tabs_fine.setSelectedTextColor(ArmsUtils.getColor(this, R.color.theme_color));
        // 设置Tab标题文字的大小
        tabs_fine.setTextSize(12);
        //设置Tab底部分割线的颜色
        tabs_fine.setUnderlineColor(Color.TRANSPARENT);
        // 设置点击某个Tab时的背景色,设置为0时取消背景色
        tabs_fine.setTabBackground(0);
        // 设置Tab是自动填充满屏幕的
        tabs_fine.setShouldExpand(true);
        //设置布局样式
        tabs_fine.setIconAndText(PagerSlidingTabStrip.TABTEXT);
        //设置文本
        tabs_fine.setTabTexts(tabTitles);
        //tab间的分割线
        tabs_fine.setDividerColor(Color.TRANSPARENT);
        //底部横线与字体宽度一致
        tabs_fine.setIndicatorinFollower(false);
        //与ViewPager关联，这样指示器就可以和ViewPager联动
        tabs_fine.setViewPager(pager_fine);
        pager_fine.setOffscreenPageLimit(2);

        pager_fine.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentFinePage = position;
                if (currentFinePage == 0) {
                    LoganManager.w_tableMode(TAG, LoganManager.EVENT_CLICK + "口味");
                    tv_fine_type.setText("口味");
                } else {
                    LoganManager.w_tableMode(TAG, LoganManager.EVENT_CLICK + "訊息");
                    tv_fine_type.setText("訊息");
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        initFineItemLayout = true;

        setCurrentFinePage();

        showViewModeVisibility(MealConstant.fine_ViewMode, MealConstant.fine_tabs_ViewMode);
    }

    @Override
    public void setCurrentFinePage() {
        if (currentFinePage == 0) {
            tv_fine_type.setText("口味");
        } else {
            tv_fine_type.setText("訊息");
        }
        pager_fine.setCurrentItem(currentFinePage);
    }

    @Override
    public void setPluMode() {
        isPluMode = (boolean) SPUtils.get(MealConstant.EXIT_IS_PLU_MODE, false);
        if (isPluMode) {
            showViewModeVisibility(MealConstant.ViewMode_keys);
            btn_fid.setBackgroundColor(ArmsUtils.getColor(this, R.color.theme_hint_color));
        } else {
            btn_fid.setBackground(ArmsUtils.getDrawablebyResource(this, R.drawable.ui_selector_item_background));
        }
    }

    @Override
    public void resetPluMode() {
        isPluMode = false;
        SPUtils.put(MealConstant.EXIT_IS_PLU_MODE, false);
        btn_fid.setBackground(ArmsUtils.getDrawablebyResource(this, R.drawable.ui_selector_item_background));
    }

    @OnLongClick({R2.id.btn_meal_delete, R2.id.btn_order_printer})
    public boolean onLongClick1(View view) {

        //记录操作 并且震动
        recordOperat(true);

        int id = view.getId();
        if (id == R.id.btn_meal_delete) {
            mPresenter.deleteFoodItem(2);
        } else if (id == R.id.btn_order_printer) {

        }
        return false;
    }

    @OnClick(R2.id.btn_meal_discount)
    void onClickDiscount() {

        LoganManager.w_tableMode(TAG, LoganManager.EVENT_CLICK + "食品折扣");

        OrderDetail mainOrderDetail = mPresenter.getSelectMealAdapter().getCurrentMainOrderDetail();
        if (mainOrderDetail != null && mainOrderDetail.getAblediscount() == 0) {
            showMessage("此食品不能參與折扣!");
            return;
        }
        //更新折扣数据
        mPresenter.loadDiscountData();

        showViewModeVisibility(MealConstant.discount_ViewMode);
    }

    @OnClick(R2.id.btn_table)
    void onClickTable() {
        if (BaseOrder.isCurrentOrderType(FoodSummaryConstans.TAKEAWAY_TYPE)) {
            return;
        }
        LoganManager.w_tableMode(TAG, LoganManager.EVENT_CLICK + "餐檯名稱");
        //type取值：1:qrCdoetype，2:手機號，3:memberId
        if (mUseMemberDialog == null) {
            mUseMemberDialog = new UseMemberDialog(this)
                    .setOnLayoutClickListener(new UseMemberDialog.OnLayoutClickListener() {

                        @Override
                        public void onInputPhone(UseMemberDialog dialog, String phone) {
                            TableBean.DataBean dataBean = DoshokuOrder.getInstance().getOpenTableInfo();
                            mPresenter.queryMember(2, phone, RestaurantInfoManager.newInstance().getGsPosShopId(), dataBean.getId(), dataBean.getTableNumber());
                        }

                        @Override
                        public void onScanAction(UseMemberDialog dialog) {
                            mPresenter.startScanActivity();
                        }

                        @Override
                        public void onUseMember(UseMemberDialog dialog) {
                            if (mMemberInfo != null) {
                                dialog.dismiss();
                                if (DoshokuOrder.getInstance().getMemberInfo() == null) {

                                    useMember();

                                    DoshokuOrder.getInstance().setMemberInfo(mMemberInfo);

                                    //添加会员折扣行
                                    ShoppingCart shoppingCart = mPresenter.getShoppingCart();
                                    MultyDiscount multyDiscount = shoppingCart.createMemberDiscount(mMemberInfo, BillItem.BILL_ITEM_NO_ORDER_STATUS);
                                    shoppingCart.addMultyDiscount(multyDiscount);

                                    DoshokuOrder.getInstance().setBillItemStatus(DoshokuOrder.MEMBER_ITEM_TAG);

                                    mPresenter.updateBillInfo();

                                }
                            } else {
                                showMessage("請輸入正確的會員號碼!");
                            }
                        }

                        @Override
                        public void clearMemberInfo() {
                            btn_table.setBackgroundColor(Color.parseColor("#336699"));
                            DoshokuOrder.getInstance().setMemberInfo(null);

                            DiscountItem memberDiscountBillItem = (DiscountItem) mPresenter.findBillItemByClass(MemberDiscount.class);
                            if (memberDiscountBillItem != null) {
                                ShoppingCart shoppingCart = mPresenter.getShoppingCart();
                                shoppingCart.delMultyDiscount(memberDiscountBillItem.getDiscount());
                                //更新賬單信息
                                mPresenter.updateBillInfo();
                            }

                            DoshokuOrder.getInstance().setBillItemStatus(DoshokuOrder.MEMBER_ITEM_TAG);
                        }
                    });
            mUseMemberDialog.build();
        }
        mUseMemberDialog.setMemberInfo(DoshokuOrder.getInstance().getMemberInfo());
        mUseMemberDialog.show();
    }

    @Override
    public void updateMemberInfo(MemberInfo memberInfo) {
        this.mMemberInfo = memberInfo;
        if (mUseMemberDialog != null) {
            mUseMemberDialog.setMemberInfo(memberInfo);
        }
    }

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

    @OnClick(R2.id.btn_multiple_selection)
    void onClickMultipleSelection() {
        LoganManager.w_tableMode(TAG, LoganManager.EVENT_CLICK, "多选");
        currentFinePage = 0;
        if (mPresenter.getSelectMealAdapter().getSelectedMode() == SelectMealAdapter.MULTIPLE_SELECTED) {
            mPresenter.getSelectMealAdapter().setSelectedMode(SelectMealAdapter.SINGLE_SELECTED);
            btn_delete.setVisibility(View.VISIBLE);
            setSelectFunctionVisibility(View.GONE);
        } else {
            mPresenter.getSelectMealAdapter().setSelectedMode(SelectMealAdapter.MULTIPLE_SELECTED);
            btn_delete.setVisibility(View.GONE);
            setSelectFunctionVisibility(View.VISIBLE);
            loadFineItemData();
        }
        showRemarkLayout();
    }

    @OnClick(R2.id.btn_select_all)
    void onClickSelectAll() {
        LoganManager.w_tableMode(TAG, LoganManager.EVENT_CLICK, "全選");
        mPresenter.setSelectAll();
    }

    @OnClick(R2.id.btn_anti_selection)
    void onClickAntiSelection() {
        LoganManager.w_tableMode(TAG, LoganManager.EVENT_CLICK, "反選");
        mPresenter.setAntiSelect();
    }

    @OnClick({R2.id.btn_key1, R2.id.btn_key2, R2.id.btn_key3, R2.id.btn_key4, R2.id.btn_key5, R2.id.btn_keys,
            R2.id.btn_numberman, R2.id.btn_fid, R2.id.btn_meal_delete, R2.id.btn_meal_modify_restore, R2.id.btn_send_order, R2.id.tv_no_save_return, R2.id.tv_order_content,
            R2.id.btn_taste, R2.id.btn_msg, R2.id.btn_delete, R2.id.btn_end, R2.id.iv_fine_back})
    public void onClick(View v) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            String text = null;
            if (v instanceof Button) {
                Button button = (Button) v;
                text = button.getText().toString();
            } else if (v instanceof TextView) {
                TextView textView = (TextView) v;
                text = textView.getText().toString();
            }
            LoganManager.w_tableMode(TAG, LoganManager.EVENT_CLICK, text);
        }

        recordOperat(true);

        //防抖處理
        int id = v.getId();
        if (id == R.id.btn_numberman) {
            if (!BaseOrder.isTableToMeal()) {
                return;
            }
            showChoosePeopleNumDialog(true);
        } else if (id == R.id.btn_fid) {
            //搜索
            if (mCurrentViewMode == MealConstant.ViewMode_keys) {
                showViewModeVisibility(MealConstant.food_group_ViewMode, MealConstant.food_ViewMode);
                SPUtils.put(MealConstant.EXIT_IS_PLU_MODE, false);
            } else {
                showViewModeVisibility(MealConstant.ViewMode_keys);
                SPUtils.put(MealConstant.EXIT_IS_PLU_MODE, true);
            }
            setPluMode();
        } else if (id == R.id.btn_meal_delete) {
            if (mPresenter.getSelectMealAdapter().getSelectedMode() == SelectMealAdapter.MULTIPLE_SELECTED) {
                return;
            }
            mPresenter.deleteFoodItem(1);

            showViewModeVisibility(MealConstant.food_group_ViewMode, MealConstant.food_ViewMode);
            SPUtils.put(MealConstant.EXIT_IS_PLU_MODE, false);
            setPluMode();
        } else if (id == R.id.btn_meal_modify_restore) {
            mPresenter.restoreDeleteFood();
            showBtnMealModifyRestoreVisibility(false);
        } else if (id == R.id.btn_send_order) {
//            RxBindingUtils.setViewClicks(v)
//                    .subscribe(new Consumer<Object>() {
//                        @Override
//                        public void accept(Object o) throws Exception {
            if (BaseOrder.isCurrentOrderType(FoodSummaryConstans.TAKEAWAY_TYPE)) {
                CC.obtainBuilder(ComponentName.COMPONENT_DELIVERYPICK)
                        .setActionName("SendOrder")
                        .build()
                        .call();
                return;
            }
            mPresenter.sendOrder(false, null);
//                        }
//                    });
        } else if (id == R.id.tv_order_content) {
            //如果打印成功會回調
            Intent intent = new Intent(mContext, OrderContentActivity.class);
            startActivityForResult(intent, ORDER_CONTENT_CODE);
        } else if (id == R.id.tv_no_save_return) {
            returnTableActivity(true);
        } else if (id == R.id.btn_taste) {
            currentFinePage = 0;
            showRemarkLayout();
        } else if (id == R.id.btn_msg) {
            currentFinePage = 1;
            showRemarkLayout();
        } else if (id == R.id.btn_delete) {
            if (mPresenter.getSelectMealAdapter().getSelectedMode() == SelectMealAdapter.SINGLE_SELECTED) {
                //只有單選操作的時候可以刪除子項
                mPresenter.deleteChildItem();
            }
        } else if (id == R.id.btn_end) {
            mPresenter.getSelectMealAdapter().setSelectedMode(SelectMealAdapter.SINGLE_SELECTED);
            btn_delete.setVisibility(View.VISIBLE);
            setSelectFunctionVisibility(View.GONE);
            //從多選頁離開 重置選中
            mPresenter.resetSelected();
            showViewModeVisibility(MealConstant.food_group_ViewMode, MealConstant.food_ViewMode);
        } else if (id == R.id.btn_key1 || id == R.id.btn_key2 || id == R.id.btn_key3 || id == R.id.btn_key4 || id == R.id.btn_key5 || id == R.id.btn_keys) {

            int i = Integer.parseInt(v.getTag().toString());
            switch (i) {
                case 0:
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                    if (BuildConfig.DEBUG && BaseOrder.isTableToMeal()) {
                        if (i == 1) {
                            OrderResponse order = DoshokuOrder.getInstance().getOrderPlaced();
                            if (order != null) {
                                ArmsUtils.snackbarText("訂單ID:" + order.getId());
                            }
                        } else if (i == 2) {
                            MemberInfo memberInfo = DoshokuOrder.getInstance().getMemberInfo();
                            if (memberInfo != null) {
                                showMessage("積分兌現金比例: " + memberInfo.getPointRedeemCash());
                            }
                        }
                    }
                    mPresenter.changeNumber(i);
                    break;
                case 99:
                    ChooseNumberDialog mChooseNumberDialog = new ChooseNumberDialog(mContext);
                    mChooseNumberDialog.builder();
                    mChooseNumberDialog.setOnClickListener(new ChooseNumberDialog.OnClickListener() {

                        @Override
                        public void onComfirmClick(String number) {
                            int inumber = Integer.parseInt(number);
                            if (inumber == 0) {
                                return;
                            }
                            mPresenter.changeNumber(inumber);
                        }

                        @Override
                        public void onBackPage() {
                        }
                    });
                    mChooseNumberDialog.setValueHint("請輸入數量");
                    mChooseNumberDialog.setCancelable(true);
                    mChooseNumberDialog.show();
                    break;
                default:
                    break;
            }
        } else if (id == R.id.iv_fine_back) {
            showViewModeVisibility(MealConstant.combo_ViewMode);
        }
    }


    @Override
    public void onBackPressedSupport() {
//        super.onBackPressedSupport();
        returnTableActivity(true);
    }

    public void returnTableActivity(boolean initTable) {
        if (mPresenter.hasNesOrderFoods()) {
            //没有过重复下单提示且有未送单食品，提示用户
            String tip = LanguageUtils.get_language_system(this, "food.not.delivered.tip", "有食品未送單, 確認離開?");
            Class[] parameterTypes = {boolean.class};
            Object[] parameters = {initTable};
            CommonTipDialog.showSurpisedDialog(this, tip, MealStandActivity.class, this,
                    "returnBeforeActivity", parameterTypes, parameters);
        } else {
            returnBeforeActivity(initTable);
        }
    }

    public void returnBeforeActivity(boolean initTable) {
        SPUtils.put(MealConstant.EXIT_IS_PLU_MODE, isPluMode);
        if (BaseOrder.isTableToMeal() && initTable && !DoshokuOrder.getInstance().isModifyOrder()) {
            TableBean.DataBean dataBean = DoshokuOrder.getInstance().getOpenTableInfo();
            if (dataBean != null) {
                //通知更新餐台状态
                EventBus.getDefault().post(new InitTableEvent(dataBean.getId(), dataBean.getTableNumber()), "initTable_status_event");
            }
        }
        killMyself();
    }

    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();
                            returnBeforeActivity(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();
        }
    }

    @Override
    public void showChoosePeopleNumDialog(boolean isNeedCancel) {
        if (mChooseNumberDialog == null) {
            mChooseNumberDialog = new ChooseNumberDialog(this);
            mChooseNumberDialog.builder();
            mChooseNumberDialog.setValueHint("請輸入人數");
//            mInputNumberDialog2.setTitle(LanguageUtils.get_language_system(this, "Meal.Mannumber", "Number"));
//            mInputNumberDialog2.setHeadLayoutVisibility(View.VISIBLE);
            if (!isNeedCancel)
                mChooseNumberDialog.setOnBackClickListener(new ChooseNumberDialog.OnBackClickListener() {

                    @Override
                    public void OnBackClick() {
                        recordOperat(true);
                        returnTableActivity(true);
                    }
                });
            int backPageBtnVisibility;
            if (isNeedCancel) {
                backPageBtnVisibility = View.GONE;
            } else {
                backPageBtnVisibility = View.VISIBLE;
            }
            mChooseNumberDialog.setOnClickListener(new ChooseNumberDialog.OnClickListener() {

                @Override
                public void onComfirmClick(String number) {
                    recordOperat(true);
                    TableBean.DataBean dataBean = DoshokuOrder.getInstance().getOpenTableInfo();
                    int maxSeatCount = 0;
                    if (dataBean != null) {
                        maxSeatCount = dataBean.getMaxSeatCount();
                    }
                    if (maxSeatCount != 0 && maxSeatCount < Integer.parseInt(number)) {
                        showMessage("最大就餐人數不能超過" + maxSeatCount + "人!");
                        return;
                    }
                    mPresenter.updateOrderPerson(number, btn_numberman);
                }

                @Override
                public void onBackPage() {
                    returnTableActivity(true);
                }
            });
            mChooseNumberDialog.setCancelable(isNeedCancel);
        }
        mChooseNumberDialog.show();
    }

    @Override
    public void setPrinterLocalmachine(boolean isPrint) {

    }

    @Override
    public void setTableInfoDialogAdapter(BaseAdapter adapter) {

    }

    @Override
    public void setSelectFoodAdapter(RecyclerView.Adapter adapter) {
        setSelectFoodRecycleLayoutManager();
        rv_select_meal.setAdapter(adapter);
    }

    @Override
    public void setFoodGroupAdapter(DefaultAdapter adapter) {
        rv_food_group.addItemDecoration(new GridDividerItemDecoration(QMUIDisplayHelper.dpToPx(1), ArmsUtils.getColor(mContext, R.color.black)));
        rv_food_group.setAdapter(adapter);
    }

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

    @Override
    public void setOrderDetailAdapter(DefaultAdapter adapter) {

    }

    @Override
    public void setComboAdapter(DefaultAdapter adapter) {
        setComboRecycleLayoutManager(LinearLayoutManager.VERTICAL);
        rv_combo.setAdapter(adapter);
    }

    @Override
    public void setModifierAdapter(DefaultAdapter adapter) {
        setModifierRecycleLayoutManager(LinearLayoutManager.VERTICAL);
        rv_modifier.setAdapter(adapter);
    }

    @Override
    public void setDiscountAdapter(DefaultAdapter adapter) {
        setDiscountRecycleLayoutManager(LinearLayoutManager.VERTICAL);
        rv_discount.setAdapter(adapter);
    }

    private GridLayoutManager foodRecycleLayoutManager, comboRecycleLayoutManager, modifierRecycleLayoutManager, discountRecycleLayoutManager;

    @Override
    public void setSelectFoodRecycleLayoutManager() {
        RecyclerViewNoBugLinearLayoutManager selectFoodRecycleLayoutManager = new RecyclerViewNoBugLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        rv_select_meal.setLayoutManager(selectFoodRecycleLayoutManager);
//        rv_select_meal.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    public void setFoodGroupRecycleLayoutManager(int orientation) {

    }

    @Override
    public void setFoodRecycleLayoutManager(int orientation) {
        foodRecycleLayoutManager = new GridLayoutManager(this, 1, orientation, false);
        rv_food.setLayoutManager(foodRecycleLayoutManager);
        rv_food.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    public void setComboRecycleLayoutManager(int orientation) {
        comboRecycleLayoutManager = new GridLayoutManager(this, 1, LinearLayoutManager.VERTICAL, false);
        rv_combo.setLayoutManager(comboRecycleLayoutManager);
        rv_combo.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    public void setModifierRecycleLayoutManager(int orientation) {
        modifierRecycleLayoutManager = new GridLayoutManager(this, 1, LinearLayoutManager.VERTICAL, false);
        rv_modifier.setLayoutManager(modifierRecycleLayoutManager);
        rv_modifier.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    public void setDiscountRecycleLayoutManager(int orientation) {
//        FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(mContext);
//        //主轴为水平方向，起点在左端。
//        flexboxLayoutManager.setFlexDirection(FlexDirection.ROW);
//        //按正常方向换行
//        flexboxLayoutManager.setFlexWrap(FlexWrap.WRAP);
//        //交叉轴的起点对齐。
//        flexboxLayoutManager.setJustifyContent(JustifyContent.FLEX_START);
        discountRecycleLayoutManager = new GridLayoutManager(this, 4, LinearLayoutManager.VERTICAL, false);
        rv_discount.setLayoutManager(discountRecycleLayoutManager);
        rv_discount.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.HORIZONTAL_LIST));
        rv_discount.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    public void setFoodGroupRecycleSpanCount(int size) {
        DecimalFormat df = new DecimalFormat("###.00");
        String span = df.format((double) size / foodGroupColumn);
        int spanCount = (int) Math.ceil(Double.parseDouble(span));   //33.333
    }

    @Override
    public void setFoodRecycleSpanCount(int size) {
        if (size > 0) {
            if (size > foodColumn) {
                setFoodRecycleLayoutManager(LinearLayoutManager.VERTICAL);
                foodRecycleLayoutManager.setSpanCount(foodColumn);
            } else {
                //只有一行就使用水平显示以免不能占满
                setFoodRecycleLayoutManager(LinearLayoutManager.HORIZONTAL);
            }
        }
    }

    @Override
    public void setComboRecycleSpanCount(int size) {
        if (size > 0) {
//            if (size > comboRow) {
            setComboRecycleLayoutManager(LinearLayoutManager.VERTICAL);
            comboRecycleLayoutManager.setSpanCount(comboColumn);
//            } else if (size <= ComboColCount) {
//            } else  {
//                //只有一行就使用水平显示以免不能占满
//                setComboRecycleLayoutManager(LinearLayoutManager.HORIZONTAL);
//            }
        }
    }

    @Override
    public void setModifierRecycleSpanCount(int size) {
        if (size > 0) {
//            if (size > modRow) {
            setModifierRecycleLayoutManager(LinearLayoutManager.VERTICAL);
            modifierRecycleLayoutManager.setSpanCount(modColumn);
//            } else if (size <= ComboColCount) {
//            } else  {
//                //只有一行就使用水平显示以免不能占满
//                setComboRecycleLayoutManager(LinearLayoutManager.HORIZONTAL);
//            }
        }
    }

    @Override
    public void setDiscountRecycleSpanCount(int size) {
        if (size > 0) {
            setDiscountRecycleLayoutManager(LinearLayoutManager.VERTICAL);
            discountRecycleLayoutManager.setSpanCount(discountColumn);
        }
    }

    @Override
    public void showViewModeVisibility(int... viewMode) {
        //將所有的view隱藏
        for (int i = 0; i < map.size(); i++) {
            map.valueAt(i).setVisibility(View.INVISIBLE);
        }
        //設置當前mode為第一個傳入的mode
        for (int mode : viewMode) {
            this.mCurrentViewMode = mode;
            break;
        }
        //顯示所有傳入的需要顯示的view
        for (int mode : viewMode) {
            map.get(mode).setVisibility(View.VISIBLE);
        }
        //設置當前模式為輸入Plu模式
        if (viewMode != null && viewMode[0] == MealConstant.ViewMode_keys) {
            isPluMode = true;
        } else {
            isPluMode = false;
        }
        switch (mCurrentViewMode) {
            case MealConstant.food_group_ViewMode:
            case MealConstant.food_ViewMode:
                showModifyLayoutVisibility(false);
                break;
            case MealConstant.combo_ViewMode:
//            case MealConstant.modifier_ViewMode:
            case MealConstant.discount_ViewMode:
            case MealConstant.fine_ViewMode:
                showModifyLayoutVisibility(true);
                break;
            default:
                break;
        }
    }

    @Override
    public void showModifyLayoutVisibility(boolean show) {
        if (show) {
            ll_modify.setVisibility(View.VISIBLE);
            ll_stand_oper.setVisibility(View.INVISIBLE);
        } else {
            ll_modify.setVisibility(View.INVISIBLE);
            ll_stand_oper.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void setOrderFoodCount(String number) {
        if (!number.equals(0)) {
            btn_order_count.setText(number);
            btn_order_count.setVisibility(View.VISIBLE);
        } else {
            btn_order_count.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void setMealRvScrollToPosition(int position) {
        rv_select_meal.scrollToPosition(position);
    }

    @Override
    public void initIntent() {

    }

    @Override
    public void initTopBar() {

    }

    @Override
    public void initLanguage() {

    }

    @Override
    public void initLayoutParams() {

    }

    @Override
    public void initLayoutVisible() {
        if (BaseOrder.isTableToMeal() && DoshokuOrder.getInstance().isModifyOrder()) {
            //修改訂單隱藏送單功能
            fl_send_order.setVisibility(View.GONE);
        }
    }

    @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 showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(MealStandActivity.this, message);
    }

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

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

    @Override
    public Activity getActivity() {
        return this;
    }

    public void clearInput() {
        keyView.clearInput();
    }

    /**
     * 显示公共信息
     */
    public void showRemarkLayout() {
        //没有初始化细项布局则初始化
        if (!isInitFineItemLayout()) {

            initFineItemTabBarViewPage();

            loadFineItemData();

        } else {

            setCurrentFinePage();

            showViewModeVisibility(MealConstant.fine_ViewMode, MealConstant.fine_tabs_ViewMode);
        }
    }

    private void loadFineItemData() {
        if (modMsgFineItemFragment == null || modSasteFineItemFragment == null) {
            return;
        }
        long productId = 0;
        if (mPresenter.getCurrentOrderDetailBean() != null) {
            productId = mPresenter.getCurrentOrderDetailBean().getProductId();
        }
        if (mPresenter.getSelectMealAdapter().getSelectedMode() == SelectMealAdapter.SINGLE_SELECTED) {
            modMsgFineItemFragment.loadModMsgData(productId);
            modSasteFineItemFragment.loadModSasteData(productId);
        } else {
            modMsgFineItemFragment.loadModCommData(productId);
            modSasteFineItemFragment.loadModSasteData(productId);
        }
        setFineItemSlodoutListFull(mPresenter.getSoldoutCtrList());
    }

    /**
     * 設置細項沽清數據
     *
     * @param slodoutListFull
     */
    public void setFineItemSlodoutListFull(List<SoldoutCtrFood> slodoutListFull) {
        if (modMsgFineItemFragment != null) {
            modMsgFineItemFragment.setModifierSoldoutFoodList_Full(slodoutListFull);
            modMsgFineItemFragment.updateParentModifierSlodoutFoodList_Full();
        }
        if (modSasteFineItemFragment != null) {
            modSasteFineItemFragment.setModifierSoldoutFoodList_Full(slodoutListFull);
            modSasteFineItemFragment.updateParentModifierSlodoutFoodList_Full();
        }
    }

    private void initViewMap() {
        map.put(MealConstant.food_group_ViewMode, ll_food_group);
        map.put(MealConstant.food_ViewMode, rv_food);
        map.put(MealConstant.combo_ViewMode, scroll_combo);
//        map.put(MealConstant.modifier_ViewMode, rv_modifier);
        map.put(MealConstant.discount_ViewMode, rv_discount);
        map.put(MealConstant.fine_ViewMode, pager_fine);
        map.put(MealConstant.fine_tabs_ViewMode, rl_fine_tabs);
        map.put(MealConstant.ViewMode_keys, keyView);

        //            @SwitchPrintMethod
        btn_send_order.setOnLongClickListener(v -> {
            PrinterUtils.switchPrintMethod(mContext, null, null);
            return false;
        });
    }

    public FoodGroupAdapter getFoodGroupGridViewAdapter() {
        return mFoodGroupAdapter;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ORDER_CONTENT_CODE) {
            //訂單內容回調
            if (resultCode == Activity.RESULT_OK) {
                //打印成功
                //結賬成功
                //關閉當前頁面
                killMyself();
            }
        } else if (requestCode == ScanHelper.CALL_BACK_QR_RESULT) {
            String qrCodeResult = data.getStringExtra("qrCodeResult");
            if (TextUtils.isEmpty(qrCodeResult)) {
                return;
            }
            TableBean.DataBean dataBean = DoshokuOrder.getInstance().getOpenTableInfo();
            mPresenter.queryMember(1, qrCodeResult, RestaurantInfoManager.newInstance().getGsPosShopId(), dataBean.getId(), dataBean.getTableNumber());
        }
    }

    public int getCurrentViewMode() {
        return mCurrentViewMode;
    }

    @Override
    public void onPageSizeChanged(int pageSize) {
    }

    @Override
    public void onPageSelect(int pageIndex) {
        mPageIndex = pageIndex;

        LoganManager.w_tableMode(TAG, LoganManager.EVENT_SCOLL + "食品組頁=" + (pageIndex + 1));

        for (int i = 0; i < totalPage; i++) {
            if (i == pageIndex) {
                ivPoints[i].setImageResource(R.drawable.meal_food_group_point_focuese);
            } else {
                ivPoints[i].setImageResource(R.drawable.meal_food_group_point_unfocused);
            }
        }
    }

    @Override
    public void setModifierTop(int margins) {
        RelativeLayout.LayoutParams layoutParam = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParam.setMargins(0, margins, 0, 0);
        layoutParam.addRule(RelativeLayout.ABOVE, R.id.ll_stand_oper);
        layoutParam.addRule(RelativeLayout.BELOW, R.id.rv_combo);
        rv_modifier.setLayoutParams(layoutParam);
    }

    @Override
    public void setCustomFoodDialog(int customType, OrderDetail foodItem) {
        new CustomFoodDialog(mContext, customType)
                .create(R.style.MyEditDialogTheme)
                .setOnEditListener((dialog, name, money) -> {
                    dialog.dismiss();
                    if (customType == Food.CUSTOM_TYPE_101) {
                        foodItem.setProductName(name);
                    }
                    if(!TextUtils.isEmpty(money)){
                        foodItem.setUnit_price(Double.parseDouble(money));
                        foodItem.setPrice(foodItem.getUnit_price());
                        mPresenter.toAddFoodItem(foodItem);
                    }
                })
                .show();
    }

    @Override
    public void showBtnMealModifyRestoreVisibility(boolean show) {
        btn_meal_modify_restore.setVisibility(show ? View.VISIBLE : View.GONE);
    }

    private void setSelectFunctionVisibility(int visibility) {
        btn_anti_selection.setVisibility(visibility);
        btn_select_all.setVisibility(visibility);
    }

    public boolean isInitSentOrderDiscount() {
        return initSentOrderDiscount;
    }

    public void setInitSentOrderDiscount(boolean initSentOrderDiscount) {
        this.initSentOrderDiscount = initSentOrderDiscount;
    }
}
