package com.gingersoft.gsa.cloud.table.mvp.ui.fragment.mealstand;

import android.app.Activity;
import android.app.Application;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
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.ExpandConstant;
import com.gingersoft.gsa.cloud.common.constans.FoodSummaryConstans;
import com.gingersoft.gsa.cloud.common.constans.MealConstant;
import com.gingersoft.gsa.cloud.common.constans.PrintConstans;
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.restaurant.utils.RestaurantExpandInfoUtils;
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.other.SPUtils;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.database.bean.ComboItem;
import com.gingersoft.gsa.cloud.database.bean.Discount;
import com.gingersoft.gsa.cloud.database.bean.Food;
import com.gingersoft.gsa.cloud.database.bean.Modifier;
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.DoshokuOrder;
import com.gingersoft.gsa.cloud.print.bean.PrintContent;
import com.gingersoft.gsa.cloud.print.bean.adapter.PrintContentAdapter;
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.DaggerSetMealComponent;
import com.gingersoft.gsa.cloud.table.mvp.contract.SetMealContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.FoodReason;
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.bean.event.LoadFineEvent;
import com.gingersoft.gsa.cloud.table.mvp.presenter.mealstand.SetMealPresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.MealStandActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.MealStandActivity2;
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.ModifierAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.SelectMealAdapter;
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.discount.NomalDiscountFragment;
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.MyTableView;
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.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.base.delegate.IActivity;
import com.jess.arms.di.component.AppComponent;
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.QMUITabSegment;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment2;

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

import java.io.UnsupportedEncodingException;
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;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * 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 SetMealFragment extends BaseFragment<SetMealPresenter> implements SetMealContract.View, PagerGridLayoutManager.PageListener {

    @Inject
    Application mApplication;

    @BindView(R2.id.btn_table)
    Button btnTable;
    @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.rv_select_meal)
    RecyclerView rvSelectMeal;
    @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.fl_container)
    LinearLayout flContainer;

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

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

    @BindView(R2.id.ll_discount)
    LinearLayout llDiscount;
    @BindView(R2.id.tabs_discount)
    QMUITabSegment2 tabSegmentDiscount;
    @BindView(R2.id.pager_discount)
    ViewPager2 vPager2Discount;

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

    private MealStandActivity2 mActivity;

    public static final String SET_CURR_LAYOUT_EVENT = "setCurrLayoutEvent";

    private int mCurrentViewMode;
    private boolean isPluMode = false;

    private boolean isLoadFineFragment = false;
    private boolean isLoadDiscountFragment = 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;

    public static SetMealFragment newInstance() {
        SetMealFragment fragment = new SetMealFragment();
        return fragment;
    }

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

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_set_meal, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mActivity = (MealStandActivity2) _mActivity;

        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, llDiscount);
        map.put(MealConstant.keys_viewMode, mealStandSearchKeyboardView);
    }

    private void initTableInfo() {
        TableBean.DataBean dataBean = DoshokuOrder.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(rvSelectMeal);
        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) -> {
            recordOperat(true);
            mPresenter.foodItemClick(datasBean);
            LoganManager.w_tableMode(TAG, LoganManager.EVENT_ADD + "食品【" + datasBean.getFoodName() + "】");
        });
        mComboAdapter.setOnItemClickListener((datasBean, position) -> {
            recordOperat(true);
            mPresenter.comboItemClick(datasBean);
            LoganManager.w_tableMode(TAG, LoganManager.EVENT_ADD + "子食品【" + datasBean.getName() + "】");
        });
        mModifierAdapter.setOnItemClickListener((datasBean, position) -> {
            recordOperat(true);
            mPresenter.modifierItemClick(datasBean);
            LoganManager.w_tableMode(TAG, LoganManager.EVENT_ADD + "細項【" + datasBean.getName() + "】");
        });
        //Plu鍵盤
        mealStandSearchKeyboardView.setOnConfirmCallBack((inputText) -> {
            recordOperat(true);
            if (TextUtils.isEmpty(inputText)) {
                return;
            }
            mPresenter.toFindMeal(inputText);
        });
        //送單
        mActivity.setSendOrderListener(() -> {
            recordOperat(true);
            mPresenter.sendOrder(false, null);
        });
    }

    @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) {
                recordOperat(true);
                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(_mActivity);
            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);
        }
    }

    /**
     * 显示折扣
     */
    public void showDiscountLayout() {
        setCurrViewMode(MealConstant.discount_ViewMode);
        if (!isLoadDiscountFragment) {
            isLoadDiscountFragment = true;
            initDiscountViewPager();
        } else {
            vPager2Discount.setCurrentItem(0);
        }
    }

    private void initDiscountViewPager() {
        final List<String> tabList = getDiscountTabTitles();
        QMUITabBuilder builder = tabSegmentDiscount.tabBuilder();
        for (final String tabTitle : tabList) {
            QMUITab tab = builder
                    .setText(tabTitle)
                    .build(mContext);
            tabSegmentDiscount.addTab(tab);
        }
        vPager2Discount.setAdapter(new ViewPager2Adapter(this, createDiscountFragments()));
        vPager2Discount.setCurrentItem(0);
        QMUITabSegmentUtils.setNomalTabSegmentStyle(tabSegmentDiscount, vPager2Discount);
    }

    private List<String> getDiscountTabTitles() {
        List<String> tabList = new ArrayList<>();
        tabList.add("折扣");
        MemberInfo memberInfo = DoshokuOrder.getInstance().getMemberInfo();
        if (memberInfo != null) {
            tabList.add("會員錢包");
        }
        return tabList;
    }

    private List<Fragment> createDiscountFragments() {
        List<Fragment> fragments = new ArrayList<>();
        NomalDiscountFragment billDiscountFragment = NomalDiscountFragment.newInstance();
        billDiscountFragment.setOnDiscountItemClickListener(new NomalDiscountFragment.OnBillDiscountItemClickListener() {
            @Override
            public void onItemClick(Discount discount, int position) {
                recordOperat(true);
                LoganManager.w_tableMode(TAG, LoganManager.EVENT_ADD + "折扣【" + discount.getRemark() + "】");
                mPresenter.discountAndCouponClick(discount);
            }
        });
        fragments.add(billDiscountFragment);
        MemberInfo memberInfo = DoshokuOrder.getInstance().getMemberInfo();
        if (memberInfo != null) {
            CouponFragment couponFragment = CouponFragment.newInstance(CouponFragment.FOOD_LIMIT_DISCOUNT);
            couponFragment.setOnCouponItemClickListener(new CouponFragment.OnCouponItemClickListener() {
                @Override
                public void onItemClick(MemberWalletCoupon coupon, int position) {
                    recordOperat(true);
                    LoganManager.w_tableMode(TAG, LoganManager.EVENT_ADD + "優惠券【" + coupon.getCouponTypeName() + "】");
                    mPresenter.discountAndCouponClick(coupon);
                }
            });
            fragments.add(couponFragment);
        }
        return fragments;
    }

    /**
     * 显示公共細項
     */
    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<>();
        FineChildAllFragment modSasteFineItemFragment = FineChildAllFragment.newInstance(loadFineData);
        FineChildAllFragment modMsgFineItemFragment = FineChildAllFragment.newInstance(loadFineData2);
        fragments.add(modSasteFineItemFragment);
        fragments.add(modMsgFineItemFragment);
        return fragments;
    }

    @Override
    public void setData(@Nullable Object data) {

    }

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

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

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

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

    @Override
    public void killMyself() {
        _mActivity.onBackPressedSupport();
    }

    @Override
    public void showChoosePeopleNumDialog(boolean isNeedCancel) {
        ChooseNumberDialog chooseNumberDialog = new ChooseNumberDialog(_mActivity);
        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 = 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, btnNumberman);
            }

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

    @Override
    public void showCancelFoodDialog(OrderDetail deleteFood) {
        if (mCancelFoodDialog == null) {
            mCancelFoodDialog = new CancelFoodDialog(_mActivity);
            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(_mActivity);
        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);
        }
        mActivity.showStandOperLayoutVisibility(show);
    }

    @Override
    public void showBtnMealModifyRestoreVisibility(boolean show) {

    }

    @Override
    public void setOrderFoodCount(String number) {
        mActivity.setOrderFoodCount(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) {
        rvSelectMeal.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 MealStandActivity2 getActivity2() {
        return (MealStandActivity2) _mActivity;
    }

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

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

    @Override
    public void recordOperat(boolean isPressButtonSound) {
        mActivity.recordOperat(isPressButtonSound);
    }

    @Override
    public void setFoodAdapter(DefaultAdapter adapter) {

    }

    @Override
    public void setOrderDetailAdapter(DefaultAdapter adapter) {

    }

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

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

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

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

    @OnClick(R2.id.btn_anti_selection)
    void onAntiSelectionViewClick() {
        recordOperat(true);
        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) {

        recordOperat(true);

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

    @OnClick({R2.id.btn_taste, R2.id.btn_msg, R2.id.btn_delete, R2.id.btn_end})
    public void onModifyViewClick(View v) {

        recordOperat(true);

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

    public void backFoodViewMode() {
        //回復單選
        mPresenter.getSelectMealAdapter().setSelectedMode(SelectMealAdapter.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) {

        recordOperat(true);

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

    @Override
    public void onPageSizeChanged(int pageSize) {

    }

    @Override
    public void onPageSelect(int pageIndex) {
        recordOperat(false);
        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(DoshokuOrder.getInstance().getOpenTableInfo(), DoshokuOrder.getInstance().getMemberInfo());
        dialogFragment.setOnUseMemberListener(new RiceponMemberDialogFragment.OnUseMemberListener() {
            @Override
            public void onUseMember(MemberInfo memberInfo) {
                recordOperat(false);
                if (memberInfo == null) {
                    btnTable.setBackgroundColor(Color.parseColor("#336699"));
                } else {
                    btnTable.setBackgroundResource(R.color.pink_300);
                    //添加会员折扣行
                    ShoppingCart shoppingCart = mPresenter.getShoppingCart();
                    MultyDiscount multyDiscount = shoppingCart.createMemberDiscount(memberInfo, BillItem.BILL_ITEM_NO_ORDER_STATUS);
                    shoppingCart.addMultyDiscount(multyDiscount);
                    DoshokuOrder.getInstance().setBillItemStatus(DoshokuOrder.MEMBER_ITEM_TAG);
                    mPresenter.updateBillInfo();
                }
                DoshokuOrder.getInstance().setMemberInfo(memberInfo);
                dialogFragment.dismiss();
            }
        });
        dialogFragment.show(getChildFragmentManager(), dialogFragment.getClass().getSimpleName());
    }

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

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

}
