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

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

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.MealConstant;
import com.gingersoft.gsa.cloud.common.core.member.MemberInfo;
import com.gingersoft.gsa.cloud.common.core.table.TableBean;
import com.gingersoft.gsa.cloud.common.logan.LoganManager;
import com.gingersoft.gsa.cloud.common.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.database.bean.Discount;
import com.gingersoft.gsa.cloud.database.bean.Food;
import com.gingersoft.gsa.cloud.order.bean.discount.MemberWalletCoupon;
import com.gingersoft.gsa.cloud.order.bean.response.OrderResponse;
import com.gingersoft.gsa.cloud.order.billItem.BillItem;
import com.gingersoft.gsa.cloud.order.cart.ShoppingCart;
import com.gingersoft.gsa.cloud.order.commodity.OrderDetail;
import com.gingersoft.gsa.cloud.order.discount.MultyDiscount;
import com.gingersoft.gsa.cloud.order.order.BaseOrder;
import com.gingersoft.gsa.cloud.order.order.MealOrder;
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.FoodReason;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.event.LoadFineEvent;
import com.gingersoft.gsa.cloud.table.mvp.presenter.mealstand.MealStandPresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.ComboAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.FoodAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.FoodGroupAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.MealCartAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.ModifierAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.discount.CouponFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.discount.DiscountFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.mealstand.MealFineAllFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.mealstand.RiceponMemberDialogFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.CancelFoodDialog;
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.ui.adapter.ViewPager2Adapter;
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.utils.QMUITabSegmentUtils;
import com.gingersoft.gsa.cloud.ui.view.SearchKeyBoardView;
import com.gingersoft.gsa.cloud.ui.view.base.NoScrollRecyclerView;
import com.gingersoft.gsa.cloud.ui.widget.dialog.BaseRetryDialog;
import com.gyf.immersionbar.ImmersionBar;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.integration.cache.Cache;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.tab.QMUITab;
import com.qmuiteam.qmui.widget.tab.QMUITabBuilder;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment2;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

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

import javax.inject.Inject;
import javax.inject.Named;

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


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/17/2021 10:40
 * <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 BaseMealActivity<MealStandPresenter> implements MealStandContract.View, PagerGridLayoutManager.PageListener {

    @Inject
    Application mApplication;

    @BindView(R2.id.tv_no_save_return)
    TextView tvNoSaveReturn;
    @BindView(R2.id.btn_order_count)
    Button btnOrderCount;
    @BindView(R2.id.tv_order_content)
    TextView tvOrderContent;
    @BindView(R2.id.fl_order_content)
    FrameLayout flOrderContent;
    @BindView(R2.id.btn_send_order)
    Button btnSendOrder;
    @BindView(R2.id.fl_send_order)
    FrameLayout flSendOrder;
    @BindView(R2.id.btn_order_printer)
    Button btnOrderPrinter;
    @BindView(R2.id.btn_printer_machine_name)
    Button btnPrinterMachineName;
    @BindView(R2.id.fl_printer_order)
    FrameLayout flPrinterOrder;
    @BindView(R2.id.ll_stand_oper)
    LinearLayout llStandOper;

    @BindView(R2.id.btn_numberman)
    Button btnNumberman;
    @BindView(R2.id.btn_fid)
    TextView btnFid;
    @BindView(R2.id.btn_meal_delete)
    TextView btnMealDelete;
    @BindView(R2.id.btn_meal_modify_restore)
    TextView btnMealModifyRestore;
    @BindView(R2.id.btn_meal_discount)
    TextView btnMealDiscount;
    @BindView(R2.id.btn_multiple_selection)
    TextView btnMultipleSelection;
    @BindView(R2.id.ll_meal_function)
    LinearLayout llMealFunction;
    @BindView(R2.id.ll_meals_main)
    LinearLayout llMealsMain;
    @BindView(R2.id.btn_key1)
    Button btnKey1;
    @BindView(R2.id.btn_key2)
    Button btnKey2;
    @BindView(R2.id.btn_key3)
    Button btnKey3;
    @BindView(R2.id.btn_key4)
    Button btnKey4;
    @BindView(R2.id.btn_key5)
    Button btnKey5;
    @BindView(R2.id.btn_keys)
    ImageButton btnKeys;
    @BindView(R2.id.ll_Keys)
    LinearLayout llKeys;
    @BindView(R2.id.ll_meals)
    LinearLayout llMeals;
    @BindView(R2.id.rv_food_group)
    RecyclerView rvFoodGroup;
    @BindView(R2.id.ll_food_group_point)
    LinearLayout llFoodGroupPoint;
    @BindView(R2.id.ll_food_group)
    LinearLayout llFoodGroup;
    @BindView(R2.id.rv_food)
    RecyclerView rvFood;
    @BindView(R2.id.ll_food_container)
    LinearLayout llFoodContainer;

    @BindView(R2.id.meal_stand_search_keyboard_view)
    SearchKeyBoardView mealStandSearchKeyboardView;

    @BindView(R2.id.btn_select_all)
    QMUIAlphaTextView btnSelectAll;
    @BindView(R2.id.btn_anti_selection)
    QMUIAlphaTextView btnAntiSelection;
    @BindView(R2.id.btn_taste)
    QMUIAlphaTextView btnTasteAndMsg;
    @BindView(R2.id.btn_msg)
    QMUIAlphaTextView btnMsg;
    @BindView(R2.id.btn_delete)
    QMUIAlphaTextView btnDelete;
    @BindView(R2.id.btn_end)
    QMUIAlphaTextView btnEnd;
    @BindView(R2.id.ll_modify)
    LinearLayout llModify;

    @BindView(R2.id.scroll_combo)
    NestedScrollView scrollCombo;
    @BindView(R2.id.rv_combo)
    NoScrollRecyclerView rvCombo;
    @BindView(R2.id.rv_modifier)
    NoScrollRecyclerView rvModifier;

    @BindView(R2.id.fl_discount_fragment)
    FrameLayout flDiscountFragment;

    @BindView(R2.id.ll_fine)
    LinearLayout llFine;
    @BindView(R2.id.tabs_fine)
    QMUITabSegment2 tabSegmentFine;
    @BindView(R2.id.pager_fine)
    ViewPager2 vPager2Fine;

    @Inject
    FoodGroupAdapter mFoodGroupAdapter;
    @Inject
    FoodAdapter mFoodAdapter;
    @Inject
    ComboAdapter mComboAdapter;
    @Inject
    ModifierAdapter mModifierAdapter;

    @Named("comboGridLayoutManager")
    @Inject
    GridLayoutManager mComboRecycleLayoutManager;
    @Named("modifierGridLayoutManager")
    @Inject
    GridLayoutManager mModifierRecycleLayoutManager;

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

    public static final int ORDER_CONTENT_CODE = 1002;
    public static final String SET_CURR_LAYOUT_EVENT = "setCurrLayoutEvent";

    private int mCurrentViewMode;
    private boolean isPluMode = false;

    private boolean isLoadFineFragment = false;

    private ImageView[] ivPoints;
    private int totalPage;

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

    private CancelFoodDialog mCancelFoodDialog;

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

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        recordOperat(true);
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void configImmersionBar(ImmersionBar immersionBar) {
        immersionBar
                .fitsSystemWindows(true)
                .statusBarColor(R.color.theme_white_color)
                .autoDarkModeEnable(true)
                .statusBarDarkFont(true)
                .init();
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.fragment_set_meal;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        super.initData(savedInstanceState);

        initRecyclerConfiguration();
        initViewMap();
        initAdapter();
        initListener();
        initLayoutManager();
        mPresenter.initMealData();
        mPresenter.getCurrentSoldoutFood();
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.resetSelected();
        mPresenter.updateOrderFoodNumber();
        mPresenter.updateFoodSoldoutCtrData();
        initTableInfo();
    }

    @Override
    @Subscriber(tag = SET_CURR_LAYOUT_EVENT, mode = ThreadMode.MAIN)
    public void setCurrViewMode(int... viewMode) {
        if (!isCurrViewMode(viewMode)) {
            showViewModeVisibility(viewMode);
        }
    }

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

    private void initViewMap() {
        map.put(MealConstant.food_group_ViewMode, llFoodGroup);
        map.put(MealConstant.food_ViewMode, rvFood);
        map.put(MealConstant.combo_ViewMode, scrollCombo);
        map.put(MealConstant.fine_ViewMode, llFine);
        map.put(MealConstant.discount_ViewMode, flDiscountFragment);
        map.put(MealConstant.keys_viewMode, mealStandSearchKeyboardView);
    }

    private void initTableInfo() {
        TableBean.DataBean dataBean = MealOrder.getInstance().getOpenTableInfo();
        if (dataBean != null) {
            if (TextUtils.isEmpty(dataBean.getTableNumber())) {
                btnTable.setText(dataBean.getTableName());
            } else {
                btnTable.setText(dataBean.getTableName());
            }
            btnNumberman.setText("人數:" + dataBean.getPerson());
        }
    }

    private void initAdapter() {
        mPresenter.initSelectMealAdapter(rvMealCart);
        if (mFoodGroupAdapter != null) {
            rvFoodGroup.setAdapter(mFoodGroupAdapter);
        }
        if (mFoodAdapter != null) {
            rvFood.setAdapter(mFoodAdapter);
        }
        if (mComboAdapter != null) {
            rvCombo.setAdapter(mComboAdapter);
        }
        if (mModifierAdapter != null) {
            rvModifier.setAdapter(mModifierAdapter);
        }
    }

    private void initLayoutManager() {
        if (mComboRecycleLayoutManager != null) {
            rvCombo.setLayoutManager(mComboRecycleLayoutManager);
            rvCombo.setItemAnimator(new DefaultItemAnimator());
        }
        if (mModifierRecycleLayoutManager != null) {
            rvModifier.setLayoutManager(mModifierRecycleLayoutManager);
            rvModifier.setItemAnimator(new DefaultItemAnimator());
        }
    }

    public void initListener() {
        mFoodAdapter.setOnItemClickListener((datasBean, position) -> {
            mPresenter.foodItemClick(datasBean);
            LoganManager.w_tableMode(TAG, LoganManager.EVENT_ADD + "食品【" + datasBean.getFoodName() + "】");
        });
        mComboAdapter.setOnItemClickListener((datasBean, position) -> {
            mPresenter.comboItemClick(datasBean);
            LoganManager.w_tableMode(TAG, LoganManager.EVENT_ADD + "子食品【" + datasBean.getName() + "】");
        });
        mModifierAdapter.setOnItemClickListener((datasBean, position) -> {
            mPresenter.modifierItemClick(datasBean);
            LoganManager.w_tableMode(TAG, LoganManager.EVENT_ADD + "細項【" + datasBean.getName() + "】");
        });
        //Plu鍵盤
        mealStandSearchKeyboardView.setOnConfirmCallBack((inputText) -> {
            if (TextUtils.isEmpty(inputText)) {
                return;
            }
            mPresenter.toFindMeal(inputText);
        });
    }

    @Override
    public void initFoodGroupAdapter(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;
        }
        PagerGridLayoutManager layoutManager = new PagerGridLayoutManager(rows, foodGroupColumn, PagerGridLayoutManager.HORIZONTAL);
        //水平分页布局管理器
        layoutManager.setPageListener(this);
        //设置页面变化监听器
        rvFoodGroup.setLayoutManager(layoutManager);
        //设置滚动辅助工具
        PagerGridSnapHelper pageSnapHelper = new PagerGridSnapHelper();
        pageSnapHelper.attachToRecyclerView(rvFoodGroup);
        // 如果需要查看调试日志可以设置为true，一般情况忽略即可
        PagerConfig.setShowLog(true);
        rvFoodGroup.setAdapter(mFoodGroupAdapter);
        mFoodGroupAdapter.setOnItemClickListener(new FoodGroupAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Food datasBean, int position) {
                mPresenter.foodGroupItemClick(datasBean);
            }
        });
        int foodGroupBtnHeight = GsaCloudApplication.uiStyleConfiguration.getFoodGroupBtnHeightValue();
        int mParentColHeight = foodGroupBtnHeight * rows;
        //设置ViewPager适配器
        rvFoodGroup.setLayoutParams(new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                mParentColHeight));
        //添加小圆点
        ivPoints = new ImageView[totalPage];
        for (int i = 0; i < totalPage; i++) {
            //循坏加入点点图片组
            ivPoints[i] = new ImageView(mContext);
            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(mContext, 20), ArmsUtils.dip2px(mContext, 12));
            lp.leftMargin = ArmsUtils.dip2px(mContext, 5);
            ivPoints[i].setLayoutParams(lp);
            ivPoints[i].setPadding(0, 0, 0, 0);
            llFoodGroupPoint.addView(ivPoints[i]);
        }
        if (foodGroupList.size() > (rows * foodGroupColumn)) {
            llFoodGroupPoint.setVisibility(View.VISIBLE);
        } else {
            llFoodGroupPoint.setVisibility(View.GONE);
        }
    }

    @Override
    public void updateCouponSelects(boolean sticky) {
        if (sticky) {
            EventBus.getDefault().postSticky(mPresenter.getSelectsWalletCouponMapNoByCart(), CouponFragment.UPDATE_COUPON_CHECKED_STATE);
        } else {
            EventBus.getDefault().post(mPresenter.getSelectsWalletCouponMapNoByCart(), CouponFragment.UPDATE_COUPON_CHECKED_STATE);
        }
    }

    /**
     * 显示折扣
     */
    public void loadDiscountFragment() {
        DiscountFragment discountFragment = findFragment(DiscountFragment.class);
        if (discountFragment == null) {
            discountFragment = DiscountFragment.newInstance();
            discountFragment.setOnDiscountItemClickListener(new DiscountFragment.OnDiscountItemClickListener() {

                @Override
                public void onBillDiscountClick(Discount item, int position) {
                    mPresenter.discountAndCouponClick(item);
                }

                @Override
                public void onCouponClick(MemberWalletCoupon item, int position) {
                    mPresenter.discountAndCouponClick(item);
                }
            });
            loadRootFragment(R.id.fl_discount_fragment, discountFragment);
            updateCouponSelects(true);
        }
        setCurrViewMode(MealConstant.discount_ViewMode);
    }

    /**
     * 显示公共細項
     */
    public void showFineLayout(int currFinePage) {
        setCurrViewMode(MealConstant.fine_ViewMode);
        if (!isLoadFineFragment) {
            isLoadFineFragment = true;
            initFineViewPager(currFinePage);
        } else {
            vPager2Fine.setCurrentItem(currFinePage);
        }
    }

    private void initFineViewPager(int currFinePage) {
        String[] tabList = {"口味", "訊息"};
        QMUITabBuilder builder = tabSegmentFine.tabBuilder();
        for (final String tabTitle : tabList) {
            QMUITab tab = builder
                    .setText(tabTitle)
                    .build(mContext);
            tabSegmentFine.addTab(tab);
        }
        vPager2Fine.setAdapter(new ViewPager2Adapter(this, createFineFragments()));
        vPager2Fine.setCurrentItem(currFinePage);
        QMUITabSegmentUtils.setNomalTabSegmentStyle(tabSegmentFine, vPager2Fine);
    }

    private List<Fragment> createFineFragments() {
        LoadFineEvent loadFineData = mPresenter.getLoadFineData(0);
        LoadFineEvent loadFineData2 = mPresenter.getLoadFineData(1);
        List<Fragment> fragments = new ArrayList<>();
        MealFineAllFragment modSasteFineItemFragment = MealFineAllFragment.newInstance(loadFineData);
        MealFineAllFragment modMsgFineItemFragment = MealFineAllFragment.newInstance(loadFineData2);
        fragments.add(modSasteFineItemFragment);
        fragments.add(modMsgFineItemFragment);
        return fragments;
    }

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

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

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

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

    @Override
    public void showCancelFoodDialog(OrderDetail deleteFood) {
        if (mCancelFoodDialog == null) {
            mCancelFoodDialog = new CancelFoodDialog(mContext);
            mCancelFoodDialog.setOnClickListener(new CancelFoodDialog.OnClickListener() {
                @Override
                public void onItemClick(FoodReason item, int position, int deleteNumber) {
                    LoganManager.w_tableMode(TAG, LoganManager.EVENT_CLICK + "刪除原因=" + item.getContent());
                    showDeleteFoodSureDialog(deleteFood.getNumber(), deleteNumber, item.getId(), item.getContent());
                }
            });
            mCancelFoodDialog.setOnRetryListener(new BaseRetryDialog.OnRetryListener() {
                @Override
                public void onRetryClick() {
                    mPresenter.getRestaurantFoodReason();
                }
            });
        }
        mCancelFoodDialog.setMaxCancelNumber(deleteFood.getNumber());
        mCancelFoodDialog.build().show();

        mPresenter.getRestaurantFoodReason();
    }

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

    private void showDeleteFoodSureDialog(int maxNumber, int deleteNumber, int reasonId, String reason) {
        QMUIDialog.MessageDialogBuilder dialogBuilder = new QMUIDialog.MessageDialogBuilder(mContext);
        dialogBuilder.setTitleIcon(R.drawable.qmui_icon_dialog_doubt);
        dialogBuilder.setMessage("是否確認取消該食品?" + "\n取消原因 [" + reason + "]");
        dialogBuilder.addAction(0, "確認", QMUIDialogAction.ACTION_PROP_NEGATIVE, (dialog, index) -> {
            dialog.dismiss();
            if (mCancelFoodDialog != null) {
                mCancelFoodDialog.build().dismiss();
                mCancelFoodDialog = null;
            }
            LoganManager.w_tableMode(TAG, LoganManager.EVENT_CLICK + "確刪除");
            mPresenter.markDeleteFood(maxNumber, deleteNumber, reasonId, reason);
        });
        dialogBuilder.addAction("取消", (dialog, index) -> dialog.dismiss());
        dialogBuilder.create(R.style.MyDialogTheme2).show();
    }

    @Override
    public CancelFoodDialog getCancelFoodDialog() {
        return mCancelFoodDialog;
    }

    @Override
    public void setFoodGroupRecycleSpanCount(int size) {
        notifyFoodGroupAdapter();
    }

    @Override
    public void setFoodRecycleSpanCount(int size) {
        if (size > 0) {
            GridLayoutManager foodRecycleLayoutManager;
            if (size >= foodColumn) {
                foodRecycleLayoutManager = new GridLayoutManager(mContext, foodColumn, LinearLayoutManager.VERTICAL, false);
            } else {
                //只有一行就使用水平显示以免不能占满
                foodRecycleLayoutManager = new GridLayoutManager(mContext, 1, LinearLayoutManager.HORIZONTAL, false);
            }
            rvFood.setLayoutManager(foodRecycleLayoutManager);
            rvFood.setItemAnimator(new DefaultItemAnimator());
        }
        notifyFoodAdapter();
    }

    @Override
    public void setComboRecycleSpanCount(int size) {
        if (size > 0) {
            mComboRecycleLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            mComboRecycleLayoutManager.setSpanCount(comboColumn);
            rvCombo.setLayoutManager(mComboRecycleLayoutManager);
        }
        notifyComboAdapterAdapter();
    }

    @Override
    public void setModifierRecycleSpanCount(int size) {
        if (size > 0) {
            mModifierRecycleLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            mModifierRecycleLayoutManager.setSpanCount(modColumn);
            rvModifier.setLayoutManager(mModifierRecycleLayoutManager);
        }
        notifyModifierAdapterAdapter();
    }

    @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.keys_viewMode) {
            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.discount_ViewMode:
            case MealConstant.fine_ViewMode:
                showModifyLayoutVisibility(true);
                break;
            default:
                break;
        }
    }

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

    @Override
    public void showStandOperLayoutVisibility(boolean show) {
        if (show) {
            llStandOper.setVisibility(View.INVISIBLE);
        } else {
            llStandOper.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void setOrderFoodCount(String number) {
        btnOrderCount.setText(number);
    }

    @Override
    public int getCurrentViewMode() {
        return mCurrentViewMode;
    }

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

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

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

    @Override
    public void resetSelect(int position, Food datasBean) {
        mFoodAdapter.resetSelect(position, datasBean);
    }

    @Override
    public void notifyFoodGroupAdapter() {
        mFoodGroupAdapter.notifyDataSetChanged();
    }

    @Override
    public void notifyFoodAdapter() {
        mFoodAdapter.notifyDataSetChanged();
    }

    @Override
    public void notifyComboAdapterAdapter() {
        mComboAdapter.notifyDataSetChanged();
    }

    @Override
    public void notifyModifierAdapterAdapter() {
        mModifierAdapter.notifyDataSetChanged();
    }

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

    @Override
    public int getFromType() {
        return 1;
    }

    @Override
    public void clearKeyBoardInput() {
        mealStandSearchKeyboardView.clearInput();
    }

    @OnLongClick({R2.id.btn_meal_delete})
    public boolean onLongViewClick(View view) {
        //记录操作 并且震动
        int id = view.getId();
        if (id == R.id.btn_meal_delete) {
            mPresenter.deleteFoodItem(2);
        }
        return false;
    }

    @OnClick(R2.id.btn_meal_discount)
    void onDiscountViewClick() {
        LoganManager.w_tableMode(TAG, LoganManager.EVENT_CLICK + "食品折扣");
        OrderDetail mainOrderDetail = mPresenter.getSelectMealAdapter().getCurrentMainOrderDetail();
        if (mainOrderDetail != null && mainOrderDetail.getAblediscount() == 0) {
            showMessage("此食品不能參與折扣!");
            return;
        }
        loadDiscountFragment();
    }

    @OnClick(R2.id.btn_multiple_selection)
    void onMultipleSelectionViewClick() {
        LoganManager.w_tableMode(TAG, LoganManager.EVENT_CLICK, "多选");
        if (mPresenter.getSelectMealAdapter().getSelectedMode() == MealCartAdapter.MULTIPLE_SELECTED) {
            mPresenter.getSelectMealAdapter().setSelectedMode(MealCartAdapter.SINGLE_SELECTED);
            btnDelete.setVisibility(View.VISIBLE);
            setSelectFunctionVisibility(View.GONE);
        } else {
            mPresenter.getSelectMealAdapter().setSelectedMode(MealCartAdapter.MULTIPLE_SELECTED);
            btnDelete.setVisibility(View.GONE);
            setSelectFunctionVisibility(View.VISIBLE);
        }
        showFineLayout(0);
    }

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

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

    @OnClick({R2.id.btn_table, R2.id.btn_numberman, R2.id.btn_fid, R2.id.btn_meal_delete, R2.id.btn_meal_modify_restore})
    public void onMealFunctionViewClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_table) {
            showRiceponMemberDialogFragment();
        } else if (id == R.id.btn_numberman) {
            if (!BaseOrder.isTableToMeal()) {
                return;
            }
            showChoosePeopleNumDialog(true);
        } else if (id == R.id.btn_fid) {
            if (mCurrentViewMode == MealConstant.keys_viewMode) {
                setCurrViewMode(MealConstant.food_group_ViewMode, MealConstant.food_ViewMode);
                SPUtils.put(MealConstant.EXIT_IS_PLU_MODE, false);
            } else {
                setCurrViewMode(MealConstant.keys_viewMode);
                SPUtils.put(MealConstant.EXIT_IS_PLU_MODE, true);
            }
            setPluMode();
        } else if (id == R.id.btn_meal_delete) {
            mPresenter.deleteFoodItem(1);
            setCurrViewMode(MealConstant.food_group_ViewMode, MealConstant.food_ViewMode);
            setPluMode();
            SPUtils.put(MealConstant.EXIT_IS_PLU_MODE, false);
        } else if (id == R.id.btn_meal_modify_restore) {
            mPresenter.restoreDeleteFood();
        }
    }

    @OnClick({R2.id.btn_taste, R2.id.btn_msg, R2.id.btn_delete, R2.id.btn_end})
    public void onModifyViewClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_taste) {
            showFineLayout(0);
        } else if (id == R.id.btn_msg) {
            showFineLayout(1);
        } else if (id == R.id.btn_delete) {
            mPresenter.deleteChildItem();
        } else if (id == R.id.btn_end) {
            backFoodViewMode();
        }
    }

    @OnClick(R2.id.iv_fine_back)
    void onFineBackClick() {
        showViewModeVisibility(MealConstant.combo_ViewMode);
    }

    public void backFoodViewMode() {
        DiscountFragment discountFragment = findFragment(DiscountFragment.class);
        if (discountFragment != null) {
            discountFragment.killMyself();
        }
        //回復單選
        mPresenter.getSelectMealAdapter().setSelectedMode(MealCartAdapter.SINGLE_SELECTED);
        btnDelete.setVisibility(View.VISIBLE);
        setSelectFunctionVisibility(View.GONE);
        //從多選頁離開 重置選中
        mPresenter.resetSelected();
        setCurrViewMode(MealConstant.food_group_ViewMode, MealConstant.food_ViewMode);
    }

    @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})
    public void onKeyViewClick(View v) {
        int id = v.getId();
        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 = MealOrder.getInstance().getOrderPlaced();
                            if (order != null) {
                                ArmsUtils.snackbarText("訂單ID:" + order.getId());
                            }
                        } else if (i == 2) {
                            MemberInfo memberInfo = MealOrder.getInstance().getMemberInfo();
                            if (memberInfo != null) {
                                showMessage("積分兌現金比例: " + memberInfo.getPointRedeemCash());
                            }
                        }
                    }
                    mPresenter.changeNumber(i);
                    break;
                case 99:
                    ChooseNumberDialog chooseNumberDialog = new ChooseNumberDialog(mContext);
                    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;
                default:
                    break;
            }
        }
    }

    @OnClick({R2.id.btn_send_order, R2.id.tv_no_save_return, R2.id.tv_order_content})
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_send_order) {
            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, MealBillActivity.class);
            startActivityForResult(intent, MealStandActivity.ORDER_CONTENT_CODE);
        } else if (id == R.id.tv_no_save_return) {
            returnTableActivity(true);
        }
    }

    @Override
    public void onPageSizeChanged(int pageSize) {

    }

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

    private void setSelectFunctionVisibility(int visibility) {
        btnAntiSelection.setVisibility(visibility);
        btnSelectAll.setVisibility(visibility);
    }

    private void showRiceponMemberDialogFragment() {
        RiceponMemberDialogFragment dialogFragment = RiceponMemberDialogFragment.newInstance(MealOrder.getInstance().getOpenTableInfo(), MealOrder.getInstance().getMemberInfo());
        dialogFragment.setOnUseMemberListener(memberInfo -> {
            recordOperat(false);
            if (memberInfo != null) {
                //添加会员折扣行
                ShoppingCart shoppingCart = mPresenter.getShoppingCart();
                MultyDiscount multyDiscount = shoppingCart.createMemberDiscount(memberInfo, BillItem.BILL_ITEM_NO_ORDER_STATUS);
                shoppingCart.addMultyDiscount(multyDiscount);
                MealOrder.getInstance().setBillItemStatus(MealOrder.MEMBER_ITEM_TAG);
                mPresenter.updateBillInfo();
            }
            MealOrder.getInstance().setMemberInfo(memberInfo);
            useMemberState();
            dialogFragment.dismiss();
        });
        dialogFragment.show(getSupportFragmentManager(), dialogFragment.getClass().getSimpleName());
    }

    @Override
    public void returnBeforeActivity(boolean initTable) {
        SPUtils.put(MealConstant.EXIT_IS_PLU_MODE, isPluMode);
        super.returnBeforeActivity(initTable);
    }

    private boolean isCurrViewMode(int... viewModes) {
        for (int i = 0; i < viewModes.length; i++) {
            int viewMode = viewModes[i];
            if (viewMode == mCurrentViewMode) {
                return true;
            }
        }
        return false;
    }

    @Override
    public 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();
            }
        }
    }
}
