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

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
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.viewpager.widget.ViewPager;

import com.gingersoft.gsa.cloud.app.GsaCloudApplication;
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.database.bean.ComboItem;
import com.gingersoft.gsa.cloud.database.bean.Food;
import com.gingersoft.gsa.cloud.database.bean.Modifier;
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.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.SoldoutCtrFood;
import com.gingersoft.gsa.cloud.table.mvp.presenter.mealstand.SetMealPresenter;
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.widget.ChooseNumberDialog;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.CustomFoodDialog;
import com.gingersoft.gsa.cloud.ui.adapter.TabFragmentAdapter;
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.view.MyTableView;
import com.gingersoft.gsa.cloud.ui.view.base.NoScrollRecyclerView;
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.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;

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

import java.util.ArrayList;
import java.util.Arrays;
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 {

    @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_mm)
    LinearLayout llMm;
    @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.rv_combo)
    NoScrollRecyclerView rvCombo;
    @BindView(R2.id.rv_modifier)
    NoScrollRecyclerView rvModifier;
    @BindView(R2.id.scroll_combo)
    NestedScrollView scrollCombo;
    @BindView(R2.id.ll_fine)
    LinearLayout llFine;
    @BindView(R2.id.tab_fine)
    MyTableView tabFine;
    @BindView(R2.id.pager_fine)
    ViewPager pagerFine;
    @BindView(R2.id.btn_select_all)
    QMUIAlphaTextView btnSelectAll;
    @BindView(R2.id.btn_anti_selection)
    QMUIAlphaTextView btnAntiSelection;
    @BindView(R2.id.btn_taste)
    QMUIAlphaTextView btnTaste;
    @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;

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

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


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

    private MealStandActivity2 mActivity;
    public static final byte FOOD_LAYOUT = 1;
    public static final byte COMBO_LAYOUT = 2;
    public static final byte FINE_LAYOUT = 3;
    private byte mCurrLayout = FOOD_LAYOUT;

    public static final String SET_CURR_LAYOUT_EVENT = "setCurrLayoutEvent";

    private int mCurrentViewMode;
    private boolean isPluMode = false;

    /**
     * 是否已初始化 公共細項佈局
     */
    private boolean initFineLayout = false;
    /**
     * 是否已初始化 已送單的折扣
     */
    private boolean initSentOrderDiscount = 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;

    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;

        initUIStyleConfiguration();
        initViewMap();
        initAdapter();
        initLayoutManager();
        initItemClickListener();
        mPresenter.initMealData();
    }

    @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 setCurrLayout(byte layout) {
        mCurrLayout = layout;
        switch (layout) {
            case COMBO_LAYOUT:
                showViewModeVisibility(MealConstant.combo_ViewMode);
                break;
            case FINE_LAYOUT:
                showViewModeVisibility(MealConstant.fine_ViewMode);
                break;
            default:
                showViewModeVisibility(MealConstant.food_group_ViewMode, MealConstant.food_ViewMode);
                break;
        }
    }

    private void initUIStyleConfiguration() {
        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);
    }

    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 (mFoodRecycleLayoutManager != null) {
            rvFood.setLayoutManager(mFoodRecycleLayoutManager);
            rvFood.setItemAnimator(new DefaultItemAnimator());
        }
        if (mComboRecycleLayoutManager != null) {
            rvCombo.setLayoutManager(mComboRecycleLayoutManager);
            rvCombo.setItemAnimator(new DefaultItemAnimator());
        }
        if (mModifierRecycleLayoutManager != null) {
            rvModifier.setLayoutManager(mModifierRecycleLayoutManager);
            rvModifier.setItemAnimator(new DefaultItemAnimator());
        }
    }

    public void initItemClickListener() {
        mFoodAdapter.setOnItemClickListener(new FoodAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(Food datasBean, int position) {
                mActivity.recordOperat(true);
                mPresenter.foodItemClick(datasBean);
                LoganManager.w_tableMode(TAG, LoganManager.EVENT_ADD + "食品【" + datasBean.getFoodName() + "】");
            }
        });
        mComboAdapter.setOnItemClickListener(new ComboAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(ComboItem datasBean, int position) {
                mActivity.recordOperat(true);
                mPresenter.comboItemClick(datasBean);
                LoganManager.w_tableMode(TAG, LoganManager.EVENT_ADD + "子食品【" + datasBean.getName() + "】");
            }
        });
        mModifierAdapter.setOnItemClickListener(new ModifierAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Modifier datasBean, int position) {
                mActivity.recordOperat(true);
                mPresenter.modifierItemClick(datasBean);
                LoganManager.w_tableMode(TAG, LoganManager.EVENT_ADD + "細項【" + datasBean.getName() + "】");
            }
        });
    }

    /**
     * 显示公共細項
     */
    public void showFineLayout(int currFinePage) {
        //没有初始化细项布局则初始化
        if (!initFineLayout) {
            initFineLayout = true;
            initFineViewPager();
        } else {
            pagerFine.setCurrentItem(currFinePage);
        }
        setCurrLayout(SetMealFragment.FINE_LAYOUT);
    }

    private void initFineViewPager() {
        String[] fineTitles = {"口味", "信息"};
        List<Fragment> mFragments = new ArrayList<>();
        FineChildAllFragment modSasteFineItemFragment = FineChildAllFragment.newInstance();
        FineChildAllFragment modMsgFineItemFragment = FineChildAllFragment.newInstance();
        mFragments.add(modSasteFineItemFragment);
        mFragments.add(modMsgFineItemFragment);
        //实例化适配器
        TabFragmentAdapter mTabFragmentAdapter = new TabFragmentAdapter(getChildFragmentManager(), 1);
        //设置加载的Fragment集合
        mTabFragmentAdapter.setFragments(mFragments);
        //设置Viewpager的适配器
        pagerFine.setAdapter(mTabFragmentAdapter);
        //TabLayout绑定ViewPager
        tabFine.setTitles(Arrays.asList(fineTitles)).setupWithViewPager(pagerFine);

        loadFineItemData(modSasteFineItemFragment, modMsgFineItemFragment);
    }

    private void loadFineItemData(FineChildAllFragment modMsgFineItemFragment, FineChildAllFragment modSasteFineItemFragment) {
        if (modMsgFineItemFragment == null || modSasteFineItemFragment == null) {
            return;
        }
        long productId = 0;
        if (mPresenter.getCurrentOrderDetailBean() != null) {
            productId = mPresenter.getCurrentOrderDetailBean().getProductId();
        }
        if (mPresenter.getSelectMealAdapter().getSelectedMode() == SelectMealAdapter.SINGLE_SELECTED) {
            modMsgFineItemFragment.loadModMsgData(productId);
            modSasteFineItemFragment.loadModSasteData(productId);
        } else {
            modMsgFineItemFragment.loadModCommData(productId);
            modSasteFineItemFragment.loadModSasteData(productId);
        }
        /**
         * 設置沽清數據
         */
        List<SoldoutCtrFood> slodoutListFull = mPresenter.getSoldoutCtrList();
        if (modMsgFineItemFragment != null) {
            modMsgFineItemFragment.setModifierSoldoutFoodList_Full(slodoutListFull);
            modMsgFineItemFragment.updateParentModifierSlodoutFoodList_Full();
        }
        if (modSasteFineItemFragment != null) {
            modSasteFineItemFragment.setModifierSoldoutFoodList_Full(slodoutListFull);
            modSasteFineItemFragment.updateParentModifierSlodoutFoodList_Full();
        }
    }

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

    }

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

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

    @Override
    public void setFoodRecycleSpanCount(int size) {
        if (size > 0) {
            if (size >= foodColumn) {
                mFoodRecycleLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                mFoodRecycleLayoutManager.setSpanCount(foodColumn);
            } else {
                //只有一行就使用水平显示以免不能占满
                mFoodRecycleLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            }
            rvFood.setLayoutManager(mFoodRecycleLayoutManager);
        }
        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.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.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) {
        getActivity2().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.ViewMode_keys);
            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 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 mLayoutManager = new PagerGridLayoutManager(rows, foodGroupColumn, PagerGridLayoutManager.HORIZONTAL);
        //水平分页布局管理器
        mLayoutManager.setPageListener(this);
        //设置页面变化监听器
        rvFoodGroup.setLayoutManager(mLayoutManager);
        //设置滚动辅助工具
        PagerGridSnapHelper pageSnapHelper = new PagerGridSnapHelper();
        pageSnapHelper.attachToRecyclerView(rvFoodGroup);
        // 如果需要查看调试日志可以设置为true，一般情况忽略即可
        PagerConfig.setShowLog(true);
        mFoodGroupAdapter.setFoodGroupList(foodGroupList);
        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);
        }
    }

    @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 recordOperat(boolean isPressButtonSound) {

    }

    @Override
    public void setFoodAdapter(DefaultAdapter adapter) {

    }

    @Override
    public void setOrderDetailAdapter(DefaultAdapter adapter) {

    }

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

        //记录操作 并且震动
        recordOperat(true);
//
//            int id = view.getId();
//            if (id == R.id.btn_meal_delete) {
//                mPresenter.deleteFoodItem(2);
//            } else if (id == R.id.btn_order_printer) {
//
//            }
        return false;
    }

    @OnClick(R2.id.btn_meal_discount)
    void onClickDiscount() {
        LoganManager.w_tableMode(TAG, LoganManager.EVENT_CLICK + "食品折扣");
        OrderDetail mainOrderDetail = mPresenter.getSelectMealAdapter().getCurrentMainOrderDetail();
        if (mainOrderDetail != null && mainOrderDetail.getAblediscount() == 0) {
            showMessage("此食品不能參與折扣!");
            return;
        }
        if (mActivity.findFragment(SetMealFragment.class) == null) {
            loadRootFragment(R.id.fl_meal_discount, MealDiscountFragment.newInstance());
        }
//            //更新折扣数据
//            mPresenter.loadDiscountData();
//            showViewModeVisibility(MealConstant.discount_ViewMode);
    }

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

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

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

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

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

        recordOperat(true);

        //防抖處理
        int id = v.getId();
        if (id == R.id.btn_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.ViewMode_keys) {
                setCurrLayout(SetMealFragment.FOOD_LAYOUT);
                SPUtils.put(MealConstant.EXIT_IS_PLU_MODE, false);
            } else {
                showViewModeVisibility(MealConstant.ViewMode_keys);
                SPUtils.put(MealConstant.EXIT_IS_PLU_MODE, true);
            }
            setPluMode();
        } else if (id == R.id.btn_meal_delete) {
//                if (mPresenter.getSelectMealAdapter().getSelectedMode() == SelectMealAdapter.MULTIPLE_SELECTED) {
//                    return;
//                }
//                mPresenter.deleteFoodItem(1);

            setCurrLayout(SetMealFragment.FOOD_LAYOUT);
            SPUtils.put(MealConstant.EXIT_IS_PLU_MODE, false);
            setPluMode();
        } else if (id == R.id.btn_meal_modify_restore) {
//                mPresenter.restoreDeleteFood();
            showBtnMealModifyRestoreVisibility(false);
        } else if (id == R.id.btn_taste) {
            showFineLayout(0);
        } else if (id == R.id.btn_msg) {
            showFineLayout(1);
        } 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);
            btnDelete.setVisibility(View.VISIBLE);
            setSelectFunctionVisibility(View.GONE);
            //從多選頁離開 重置選中
            mPresenter.resetSelected();
            setCurrLayout(SetMealFragment.FOOD_LAYOUT);
        } else if (id == R.id.btn_key1 || id == R.id.btn_key2 || id == R.id.btn_key3 || id == R.id.btn_key4 || id == R.id.btn_key5 || id == R.id.btn_keys) {

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

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

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

    @Override
    public void 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(DoshokuOrder.getInstance().getOpenTableInfo());
        dialogFragment.setOnUseMemberListener(new RiceponMemberDialogFragment.OnUseMemberListener() {
            @Override
            public void onUseMember(MemberInfo memberInfo) {
                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.show(getChildFragmentManager(), dialogFragment.getClass().getSimpleName());
    }
}
