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

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.SparseArray;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
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.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.common.bean.TableBean;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.OpenTableManage;
import com.gingersoft.gsa.cloud.base.utils.VibratorUtils;
import com.gingersoft.gsa.cloud.base.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.database.bean.Food;
import com.gingersoft.gsa.cloud.database.utils.ComboItemDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.FoodComboDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.FoodDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.FoodModifierDaoUtils;
import com.gingersoft.gsa.cloud.print.PrinterUtils;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.constans.GoldConstants;
import com.gingersoft.gsa.cloud.table.di.component.DaggerMealStandComponent;
import com.gingersoft.gsa.cloud.table.mvp.contract.MealStandContract;
import com.gingersoft.gsa.cloud.constans.MealConstant;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.SoldoutCtrFood;
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.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.adapter.meal.FoodGroupAdapter;
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.decorator.GridDividerItemDecoration;
import com.gingersoft.gsa.cloud.ui.view.PagerSlidingTabStrip;
import com.gingersoft.gsa.cloud.ui.view.RecyclerViewNoBugLinearLayoutManager;
import com.gingersoft.gsa.cloud.ui.view.SearchKeyBoardView;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.util.QMUIDrawableHelper;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import org.simple.eventbus.EventBus;

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

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

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 BaseActivity<MealStandPresenter> implements MealStandContract.View, PagerGridLayoutManager.PageListener {

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

    @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.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)
//    ImageButton 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 ChooseNumberDialog chooseNumberDialog;

    private FragmentManager fm;
    private FineItemAllFragment modMsgFineItemFragment, modSasteFineItemFragment;

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

    private int mCurrentViewMode;
    private boolean isPluMode = 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;

    private int ComboColCount = 4;
    private int DiscountCol = 3;

    @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) {

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

//        setViewDrawableColor();
        initTableDetail();
    }

    private void initTableDetail() {
        if (OpenTableManage.getDefault().getPeopleNumber() == 0) {
            showChoosePeopleNumDialog(false);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //更新點餐信息
        mPresenter.resetSelected();
        mPresenter.updateOrderFoodNumber();
        initOrderDetail();
    }

    private void initOrderDetail() {
        TableBean.DataBean dataBean = OpenTableManage.getDefault().getTableBean();
        if (dataBean != null) {
            btn_table.setText(dataBean.getTableName());
            btn_numberman.setText("人數:" + OpenTableManage.getDefault().getPeopleNumber() + "");
        }
    }

    public void initFoodGroupView(List<Food> foodGroupList) {

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

        int Rows = GoldConstants.foodGriupRows;
        if (foodGroupList.size() <= GoldConstants.foodGriupColumns) {
            Rows = 1;
        }
        mLayoutManager = new PagerGridLayoutManager(Rows, GoldConstants.foodGriupColumns, 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;
                }
                mPresenter.setRvMealClicked(false);
                mPresenter.changedMealByParentId(datasBean.getId());
                mPresenter.setFoodSoldoutCtrData();
            }
        });

        int mParentColHeight = GsaCloudApplication.androidSetting.getLayoutFoodTypeHeight() / GsaCloudApplication.androidSetting.getFoodTypeRow() * 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);
            }
            ivPoints[i].setPadding(0, 0, 0, 0);
            ll_food_group_point.addView(ivPoints[i]);

            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) ivPoints[i].getLayoutParams();
            layoutParams.height = ll_food_group_point.getLayoutParams().height;
            layoutParams.width = ArmsUtils.getScreenWidth(this) / totalPage;
            ivPoints[i].setLayoutParams(layoutParams);
        }
        if (foodGroupList.size() > 10) {
            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 GsaCloudApplication.getRestaurantId(mContext);
    }

    @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) {
                    tv_fine_type.setText("口味");
                } else {
                    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(this, 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(this, 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() {
        //更新折扣数据
        mPresenter.loadDiscountData();

        showViewModeVisibility(MealConstant.discount_ViewMode);
    }

    @OnClick(R2.id.btn_multiple_selection)
    void onClickMultipleSelection() {
        currentFinePage = 0;
        if (mPresenter.getSelectMealAdapter().getSelectedMode() == SelectMealAdapter.MULTIPLE_SELECTED) {
            mPresenter.getSelectMealAdapter().setSelectedMode(SelectMealAdapter.SINGLE_SELECTED);
            setSelectFunctionVisibility(View.GONE);
        } else {
            mPresenter.getSelectMealAdapter().setSelectedMode(SelectMealAdapter.MULTIPLE_SELECTED);
            setSelectFunctionVisibility(View.VISIBLE);
            loadFineItemData();
        }
        showRemarkLayout();
    }

    @OnClick(R2.id.btn_select_all)
    void onClickSelectAll() {
        mPresenter.setSelectAll();
    }

    @OnClick(R2.id.btn_anti_selection)
    void onClickAntiSelection() {
        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_send_order, R2.id.tv_no_save_return, R2.id.fl_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) {

        recordOperat(true);

        int id = v.getId();
        if (id == R.id.btn_numberman) {
            showChoosePeopleNumDialog(true);
        } else if (id == R.id.btn_fid) {
            //搜索
            if (mCurrentViewMode == MealConstant.ViewMode_keys) {
                showViewModeVisibility(MealConstant.food_group_ViewMode, MealConstant.food_ViewMode);
            } else {
                showViewModeVisibility(MealConstant.ViewMode_keys);
            }
            setPluMode();
        } else if (id == R.id.btn_meal_delete) {
            if (mPresenter.getSelectMealAdapter().getSelectedMode() == SelectMealAdapter.MULTIPLE_SELECTED)
                return;
            mPresenter.deleteFoodItem(1);
        } else if (id == R.id.btn_send_order) {
            mPresenter.sendOrder(false);
        } else if (id == R.id.fl_order_content) {
            //如果打印成功會回調
            Intent intent = new Intent(this, OrderContentActivity.class);
            startActivityForResult(intent, ORDER_CONTENT_CODE);
        } else if (id == R.id.tv_no_save_return) {
            returnBeforeActivity(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);
            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:
                    mPresenter.changeNumber(i);
                    break;
                case 99:
                    ChooseNumberDialog chooseNumberDialog = new ChooseNumberDialog(this);
                    chooseNumberDialog.builder();
                    chooseNumberDialog.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() {
                        }
                    });
                    chooseNumberDialog.setValueHint("請輸入數量");
                    chooseNumberDialog.setCancelable(true);
                    chooseNumberDialog.show();
                    break;
            }
        } else if (id == R.id.iv_fine_back) {
            showViewModeVisibility(MealConstant.combo_ViewMode,MealConstant.modifier_ViewMode);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        returnBeforeActivity(true);
    }

    public void returnBeforeActivity(boolean initTable) {
        SPUtils.put(this, MealConstant.EXIT_IS_PLU_MODE, isPluMode);
        if (initTable && OpenTableManage.getDefault().getTableBean() != null && !MyOrderManage.getInstance().isModifyOrder()) {
            //通知更新餐台状态
            EventBus.getDefault().post(OpenTableManage.getDefault().getTableBean().getId(), "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秒
                        if (SystemClock.elapsedRealtime() - chronometer.getBase() > GsaCloudApplication.androidSetting.getAutoQuitTime() * 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 (chooseNumberDialog == null) {
            chooseNumberDialog = new ChooseNumberDialog(this);
            chooseNumberDialog.builder();
            chooseNumberDialog.setValueHint("請輸入人數");
//            mInputNumberDialog2.setTitle(LanguageUtils.get_language_system(this, "Meal.Mannumber", "Number"));
//            mInputNumberDialog2.setHeadLayoutVisibility(View.VISIBLE);
            if (!isNeedCancel)
                chooseNumberDialog.setOnBackClickListener(new ChooseNumberDialog.OnBackClickListener() {

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

                @Override
                public void onComfirmClick(String number) {
                    recordOperat(true);
                    mPresenter.updateOrderPerson(number, btn_numberman);
                }

                @Override
                public void onBackPage() {
                    returnBeforeActivity(true);
                }
            });
            chooseNumberDialog.setCancelable(isNeedCancel);
        }
        chooseNumberDialog.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) {
        discountRecycleLayoutManager = new GridLayoutManager(this, 1, LinearLayoutManager.VERTICAL, false);
        rv_discount.setLayoutManager(discountRecycleLayoutManager);
        rv_discount.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    public void setFoodGroupRecycleSpanCount(int size) {
    }

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

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

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

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

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

    @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 (MyOrderManage.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.onModMsgMidEvent(productId);
            modSasteFineItemFragment.onModSasteEvent(productId);
        } else {
            modMsgFineItemFragment.onModCommMidEvent(productId);
            modSasteFineItemFragment.onModSasteEvent(productId);
        }
        setFineItemSlodoutListFull(mPresenter.getSoldoutCtrList());
    }

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

    private void initViewMap() {
        map.put(MealConstant.food_group_ViewMode, ll_food_group);
        map.put(MealConstant.food_ViewMode, rv_food);
        map.put(MealConstant.combo_ViewMode, rv_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();
            }
        }
    }

    public int getCurrentViewMode() {
        return mCurrentViewMode;
    }

    @Override
    public void onPageSizeChanged(int pageSize) {
    }

    @Override
    public void onPageSelect(int pageIndex) {
        mPageIndex = pageIndex;
        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);
    }

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

    private void setViewDrawableColor() {
        Drawable tasteDrawable = ArmsUtils.getDrawablebyResource(this, R.mipmap.meal_fine_taste);
        QMUIDrawableHelper.setDrawableTintColor(tasteDrawable, ArmsUtils.getColor(mContext, R.color.theme_white_color));
        tasteDrawable.invalidateSelf();

        Drawable msgDrawable = ArmsUtils.getDrawablebyResource(this, R.mipmap.meal_fine_info);
        QMUIDrawableHelper.setDrawableTintColor(msgDrawable, ArmsUtils.getColor(mContext, R.color.theme_white_color));
        msgDrawable.invalidateSelf();

        Drawable commDrawable = ArmsUtils.getDrawablebyResource(this, R.mipmap.meal_fine_info);
        QMUIDrawableHelper.setDrawableTintColor(commDrawable, ArmsUtils.getColor(mContext, R.color.theme_white_color));
        commDrawable.invalidateSelf();

        Drawable deleteDrawable = ArmsUtils.getDrawablebyResource(this, R.mipmap.meal_fine_delete);
        QMUIDrawableHelper.setDrawableTintColor(deleteDrawable, ArmsUtils.getColor(mContext, R.color.theme_white_color));
        deleteDrawable.invalidateSelf();

        Drawable endDrawable = ArmsUtils.getDrawablebyResource(this, R.mipmap.meal_fine_end);
        QMUIDrawableHelper.setDrawableTintColor(endDrawable, ArmsUtils.getColor(mContext, R.color.theme_white_color));
        endDrawable.invalidateSelf();

        tasteDrawable.setBounds(tasteDrawable.getMinimumWidth(), 0, 0, tasteDrawable.getMinimumHeight());
        msgDrawable.setBounds(msgDrawable.getMinimumWidth(), 0, 0, msgDrawable.getMinimumHeight());
        commDrawable.setBounds(commDrawable.getMinimumWidth(), 0, 0, commDrawable.getMinimumHeight());
        deleteDrawable.setBounds(deleteDrawable.getMinimumWidth(), 0, 0, deleteDrawable.getMinimumHeight());
        endDrawable.setBounds(endDrawable.getMinimumWidth(), 0, 0, endDrawable.getMinimumHeight());

        btn_taste.setCompoundDrawables(tasteDrawable, null, null, null);
        btn_msg.setCompoundDrawables(msgDrawable, null, null, null);
        btn_delete.setCompoundDrawables(deleteDrawable, null, null, null);
        btn_end.setCompoundDrawables(endDrawable, null, null, null);
    }

}
