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

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.base.utils.VibratorUtils;
import com.gingersoft.gsa.cloud.base.utils.log.LogUtil;
import com.gingersoft.gsa.cloud.constans.GoldConstants;
import com.gingersoft.gsa.cloud.constans.MealConstant;
import com.gingersoft.gsa.cloud.database.bean.Food;
import com.gingersoft.gsa.cloud.database.utils.ComboItemDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.FoodComboDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.FoodDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.FoodModifierDaoUtils;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.table.di.component.DaggerSoldoutCtrlComponent;
import com.gingersoft.gsa.cloud.table.mvp.contract.SoldoutCtrlContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.SoldoutCtrFood;
import com.gingersoft.gsa.cloud.table.mvp.presenter.SoldoutCtrlPresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.FineItemAllFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.FoodGroupAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.FineItemOneselfFragment;
import com.gingersoft.gsa.cloud.table.mvp.ui.widget.ChooseNumberDialog;
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.RecyclerViewNoBugLinearLayoutManager;
import com.gingersoft.gsa.cloud.ui.widget.dialog.CommonTipDialog;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseFragmentActivity;
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.arch.QMUIFragmentPagerAdapter;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.qmuiteam.qmui.widget.tab.QMUITab;
import com.qmuiteam.qmui.widget.tab.QMUITabBuilder;
import com.qmuiteam.qmui.widget.tab.QMUITabIndicator;
import com.qmuiteam.qmui.widget.tab.QMUITabSegment;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
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 butterknife.BindView;
import butterknife.OnClick;

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

/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/22/2020 10:39
 * <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 SoldoutCtrlActivity extends BaseFragmentActivity<SoldoutCtrlPresenter> implements SoldoutCtrlContract.View, PagerGridLayoutManager.PageListener {

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

    @BindView(R2.id.tv_sold_hmmc)
    TextView tv_sold_hmmc;
    @BindView(R2.id.tv_sold_hmsl)
    TextView tv_sold_hmsl;
    @BindView(R2.id.ll_stand_oper)
    LinearLayout ll_stand_oper;

    @BindView(R2.id.ll_food_group)
    LinearLayout ll_food_group;
    @BindView(R2.id.ll_food_group_point)
    LinearLayout ll_food_group_point;

    @BindView(R2.id.recycle_current_soldout_food)
    RecyclerView recycle_current_soldout_food;
    @BindView(R2.id.recycle_food_group)
    RecyclerView recycle_food_group;
    @BindView(R2.id.recycle_food)
    RecyclerView recycle_food;
    @BindView(R2.id.recycle_combo)
    RecyclerView recycle_combo;

    @BindView(R2.id.ll_fine_item)
    LinearLayout ll_fine_item;//细项操作
    @BindView(R2.id.tabSegment)
    QMUITabSegment mTabSegment;
    @BindView(R2.id.contentViewPager)
    ViewPager mContentViewPager;

    @BindView(R2.id.tv_soldout)
    TextView tv_soldout;
    @BindView(R2.id.tv_restore)
    TextView tv_restore;
    @BindView(R2.id.tv_return)
    TextView tv_return;
//    @BindView(R2.id.btn_adddelete)
//    Button btn_adddelete;
//    @BindView(R2.id.btn_msg)
//    Button btn_msg;
//    @BindView(R2.id.btn_delete)
//    Button btn_delete;
//    @BindView(R2.id.btn_end)
//    Button btn_end;


    private int mCurrentViewMode;
    private String[] mTypeItem = {"沽清控制-食品組", "沽清控制-食品", "沽清控制-細項"};
    /**
     * 1-食品組
     * 2-食品
     * 3-細項
     * 默認為食品
     */
    private int mSoldoutType = 2;
    public static final int FOOD_GROUP_TYPE = 1;
    public static final int FOOD_TYPE = 2;
    public static final int MODIFIER_TYPE = 3;

    private FineItemOneselfFragment oneselfFineItemFragment;
    private FineItemAllFragment modMsgFineItemFragment, modSasteFineItemFragment;
    private String[] mFineTabTitles = {"子項", "口味", "特別信息"};
    //    private String[] mFineTabTitles = {"口味", "特別信息"};
    private int mCurrentFinePageIndex;

    private boolean mInitModData = false;

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

    private int mParentRowCount;
    private int mParentColCount;
    private int mDetailColCount = 1;


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

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

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

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

        initViewMap();
        initTabAndPager();
        //初始化Recyclerview高度
        initRecyclerHeight();
        //初始化适配器
        mPresenter.initAdapter();
        //初始化食品數據
        mPresenter.initFoodData();
        mPresenter.initFoodListener();
        //初始化细项控制按钮点击事件
//        mPresenter.initFineItemButtonListener(this, btn_adddelete, btn_msg, btn_delete, btn_end);
    }

    private void initViewMap() {
        map.put(MealConstant.food_group_ViewMode, ll_food_group);
        map.put(MealConstant.food_ViewMode, recycle_food);
        map.put(MealConstant.combo_ViewMode, recycle_combo);
        map.put(MealConstant.fine_ViewMode, ll_fine_item);
    }

    @Override
    public void initIntent() {
    }

    @Override
    public void initTopBar() {
    }

    @Override
    public void initLanguage() {
        tv_sold_hmmc.setText(LanguageUtils.get_language_system(this, "soldout_head_name", "項目名稱"));
        tv_sold_hmsl.setText(LanguageUtils.get_language_system(this, "soldout_head_number", "數量"));
    }

    @Override
    public void initLayoutParams() {
    }

    @Override
    public void initLayoutVisible() {
    }

    private void initRecyclerHeight() {
        int screenHeidth = ArmsUtils.getScreenHeidth(this);
        LinearLayout.LayoutParams para1 = (LinearLayout.LayoutParams) recycle_current_soldout_food.getLayoutParams();
        para1.height = screenHeidth * 33 / 100;
        recycle_current_soldout_food.setLayoutParams(para1);

        mParentRowCount = GsaCloudApplication.androidSetting.getFoodTypeRow();
        mParentColCount = GsaCloudApplication.androidSetting.getFoodTypeCol();
        mDetailColCount = GsaCloudApplication.androidSetting.getFoodCol();
    }

    public void initFoodGroupView(List<Food> foodGroupList) {

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

        int Rows = GoldConstants.foodGriupRows;
        if (foodGroupList.size() <= GoldConstants.foodGriupColumns) {
            Rows = 1;
        }
        mLayoutManager = new PagerGridLayoutManager(Rows, GoldConstants.foodGriupColumns, PagerGridLayoutManager.HORIZONTAL);

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

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

        // 使用原生的 Adapter 即可
        mFoodGroupAdapter = new FoodGroupAdapter(this, foodGroupList, 2);
        mFoodGroupAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
                int count = mFoodGroupAdapter.getItemCount();

            }
        });
        recycle_food_group.setAdapter(mFoodGroupAdapter);

        mFoodGroupAdapter.setOnItemClickListener(new FoodGroupAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Food datasBean, int position) {

                VibratorUtils.pressButtonSound(SoldoutCtrlActivity.this);

                datasBean.setSelected(true);

                if (mSoldoutType == FOOD_GROUP_TYPE) {
                    //操作類型(暂停操作、恢复操作)
                    boolean isStopOpeart = false;
                    for (SoldoutCtrFood csf : mPresenter.getCurrentSlodoutFoodList_Full()) {
                        if (csf.getType() == FOOD_GROUP_TYPE &&
                                csf.getFoodId() != null && datasBean.getId() != null &&
                                csf.getFoodId().equals(datasBean.getId())) {
                            if (!TextUtils.isEmpty(csf.getQtyName())) {
                                isStopOpeart = true;
                                //恢復暫停數量
                                String msg = LanguageUtils.get_language_system(SoldoutCtrlActivity.this, "whether.recover", "是否恢復[") + datasBean.getFoodName() + "]";
                                Class[] parameterTypes = {Long.class, int.class, int.class};
                                Object[] parameters = {datasBean.getId(), 1, 0};
                                CommonTipDialog.showDoubtDialog(SoldoutCtrlActivity.this, msg, SoldoutCtrlPresenter.class, mPresenter, "updateInvisible", parameterTypes, parameters);
                                break;
                            }
                        }
                    }
                    if (!isStopOpeart) {
                        String msg = LanguageUtils.get_language_system(SoldoutCtrlActivity.this, "whether.suspend.group", "是否暫停組別?") + datasBean.getFoodName() + "\"?";
                        Class[] parameterTypes = {Long.class, int.class, int.class};
                        Object[] parameters = {datasBean.getId(), 1, 2};
                        CommonTipDialog.showDoubtDialog(SoldoutCtrlActivity.this, msg, SoldoutCtrlPresenter.class, mPresenter, "updateInvisible", parameterTypes, parameters);
                    }
                } else {
                    mPresenter.changedMealByParentId(datasBean.getId());
                    mPresenter.updateFoodSoldoutCtrData(mPresenter.getCurrentSlodoutFoodList_Full());
                }
            }
        });

        int mParentColHeight = GsaCloudApplication.androidSetting.getLayoutFoodTypeHeight() / GsaCloudApplication.androidSetting.getFoodTypeRow() * Rows;

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

        //添加小圆点
        ivPoints = new ImageView[totalPage];
        for (int i = 0; i < totalPage; i++) {
            //循坏加入点点图片组
            ivPoints[i] = new ImageView(this);
            if (i == 0) {
                ivPoints[i].setImageResource(R.drawable.meal_food_group_point_focuese);
            } else {
                ivPoints[i].setImageResource(R.drawable.meal_food_group_point_unfocused);
            }
            ivPoints[i].setPadding(0, 0, 0, 0);
            ll_food_group_point.addView(ivPoints[i]);

            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) ivPoints[i].getLayoutParams();
            layoutParams.height = ll_food_group_point.getLayoutParams().height;
            layoutParams.width = ArmsUtils.getScreenWidth(this) / totalPage;
            ivPoints[i].setLayoutParams(layoutParams);
        }
        if (foodGroupList.size() > 10) {
            ll_food_group_point.setVisibility(View.VISIBLE);
        } else {
            ll_food_group_point.setVisibility(View.GONE);
        }
    }

    @OnClick({R2.id.tv_restore, R2.id.tv_return, R2.id.iv_fine_item_back, R2.id.tv_soldout})
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_return) {
            if (mCurrentViewMode == MealConstant.fine_ViewMode) {
//                mSoldoutType = FOOD_TYPE;
//                tv_soldout.setText(mTypeItem[1]);
                mPresenter.filterSlodoutData(false);
                showViewModeVisibility(MealConstant.food_group_ViewMode, MealConstant.food_ViewMode);
            } else {
                killMyself();
            }
        } else if (id == R.id.tv_soldout) {
            showClearControlDialog();
        } else if (id == R.id.iv_fine_item_back) {
            ll_fine_item.setVisibility(View.INVISIBLE);
            recycle_food_group.setVisibility(View.VISIBLE);
            recycle_food.setVisibility(View.VISIBLE);
        } else if (id == R.id.tv_restore) {
            List<SoldoutCtrFood> soldoutCtrFoodList = getSoldoutCtrFoodList();
            if (soldoutCtrFoodList.size() == 0) {
                return;
            }
            if (soldoutCtrFoodList.size() == 1) {
                executeSingleRestore(soldoutCtrFoodList.get(0));
            } else {
                executeMultipleRestore(soldoutCtrFoodList);
            }
        }
    }

    private List<SoldoutCtrFood> getSoldoutCtrFoodList() {
        List<SoldoutCtrFood> selectSoldoutCtrFoodList = new ArrayList<>();
        List<SoldoutCtrFood> soldoutCtrFoodList = mPresenter.getCurrentSlodoutFoodList();
        for (int i = 0; i < soldoutCtrFoodList.size(); i++) {
            SoldoutCtrFood soldoutCtrFood = soldoutCtrFoodList.get(i);
            if (soldoutCtrFood.getSelected() == 1) {
                selectSoldoutCtrFoodList.add(soldoutCtrFood);
            }
        }
        return selectSoldoutCtrFoodList;
    }

    private void executeSingleRestore(SoldoutCtrFood datasBean) {
        if (datasBean.isStop()) {
            long id;
            if (datasBean.getType() == MODIFIER_TYPE) {
                id = datasBean.getModifierId();
            } else {
                id = datasBean.getFoodId();
            }                    //恢復暫停數量
            String msg = LanguageUtils.get_language_system(this, "whether.recover", "是否恢復[") + datasBean.getFoodName() + "]";
            Class[] parameterTypes = {Long.class, int.class, int.class};
            Object[] parameters = {id, datasBean.getType(), 0};
            CommonTipDialog.showDoubtDialog(this, msg, SoldoutCtrlPresenter.class, mPresenter, "updateInvisible", parameterTypes, parameters);
        } else {
            //恢復沽清數量
            String msg = LanguageUtils.get_language_system(this, "whether.recover", "是否恢復[") + datasBean.getName() + "]";
            Class[] parameterTypes = {long.class};
            Object[] parameters = {datasBean.getId()};
            CommonTipDialog.showDoubtDialog(this, msg, SoldoutCtrlPresenter.class, mPresenter, "restoreSoldoutCtrl", parameterTypes, parameters);
        }
    }

    private void executeMultipleRestore(List<SoldoutCtrFood> selectSoldoutCtrFoodList) {
        showBatchSoldoutDialog(this, "是否恢復選中食品", selectSoldoutCtrFoodList);
    }

    /**
     * 獲取需要恢復的暫停食品數據
     *
     * @return
     */
    private String[] getStopSoldoutCtrFoodIds(List<SoldoutCtrFood> selectSoldoutCtrFoodList) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < selectSoldoutCtrFoodList.size(); i++) {
            SoldoutCtrFood soldoutCtrFood = selectSoldoutCtrFoodList.get(i);
            if (soldoutCtrFood.isStop() && soldoutCtrFood.getFoodId() != null) {
                builder.append(soldoutCtrFood.getId());
                builder.append(",");
            }
        }
        String str = builder.toString();
        if (str.endsWith(",")) {
            str = str.substring(0, str.length() - 1);
        }
        return str.split(",");
    }

    /**
     * 獲取需要恢復的暫停食品數據
     *
     * @return
     */
    private String[] getStopSoldoutCtrModifierIds(List<SoldoutCtrFood> selectSoldoutCtrModifierList) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < selectSoldoutCtrModifierList.size(); i++) {
            SoldoutCtrFood soldoutCtrModifier = selectSoldoutCtrModifierList.get(i);
            if (soldoutCtrModifier.isStop() && soldoutCtrModifier.getModifierId() != null) {
                builder.append(soldoutCtrModifier.getId());
                builder.append(",");
            }
        }
        String str = builder.toString();
        if (str.endsWith(",")) {
            str = str.substring(0, str.length() - 1);
        }
        return str.split(",");
    }

    /**
     * 獲取需要恢復的庫存數據
     *
     * @return
     */
    private String getNumberSoldoutIds(List<SoldoutCtrFood> selectSoldoutCtrFoodList) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < selectSoldoutCtrFoodList.size(); i++) {
            SoldoutCtrFood soldoutCtrFood = selectSoldoutCtrFoodList.get(i);
            if (!soldoutCtrFood.isStop()) {
                builder.append(soldoutCtrFood.getId());
                builder.append(",");
            }
        }
        String str = builder.toString();
        if (str.endsWith(",")) {
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }

    private void showBatchSoldoutDialog(Activity context, String msg, List<SoldoutCtrFood> selectSoldoutCtrFoodList) {
        QMUIDialog.MessageDialogBuilder dialogBuilder = new QMUIDialog.MessageDialogBuilder(context);
        dialogBuilder.setTitleIcon(com.gingersoft.gsa.cloud.base.R.drawable.qmui_icon_dialog_doubt);
        dialogBuilder.setMessage(msg);
        dialogBuilder.addAction(com.gingersoft.gsa.cloud.base.R.drawable.shape_red_five_radius_bg, "確認", QMUIDialogAction.ACTION_PROP_NEGATIVE, (dialog, index) -> {
            dialog.dismiss();
            String[] foodIds = getStopSoldoutCtrFoodIds(selectSoldoutCtrFoodList);
            String[] modifierIds = getStopSoldoutCtrModifierIds(selectSoldoutCtrFoodList);
            String ids = getNumberSoldoutIds(selectSoldoutCtrFoodList);
            if (!TextUtils.isEmpty(foodIds[0]) || !TextUtils.isEmpty(modifierIds[0])) {
                mPresenter.batchUpdateInvisible(foodIds, modifierIds, 2);
            }
            if (ids.length() > 0) {
                mPresenter.batchRestoreSoldoutCtrl(ids);
            }
        });
        dialogBuilder.addAction(com.gingersoft.gsa.cloud.base.R.drawable.shape_3c_cancel_btn_bg, "取消", (dialog, index) -> dialog.dismiss());
        dialogBuilder.create(com.gingersoft.gsa.cloud.base.R.style.MyDialogTheme2).show();
    }

    private void showClearControlDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("沽清控制");
        builder.setSingleChoiceItems(mTypeItem, (mSoldoutType - 1), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tv_soldout.setText(mTypeItem[which]);
                mSoldoutType = which + 1;
                //选择食品组需要收起食品、细项显示数据
                switch (mSoldoutType) {
                    case FOOD_GROUP_TYPE:
                        showViewModeVisibility(MealConstant.food_group_ViewMode);
                        break;
                    case FOOD_TYPE:
                        showViewModeVisibility(MealConstant.food_group_ViewMode, MealConstant.food_ViewMode);
                        break;
                    case MODIFIER_TYPE:
//                        if (!mInitModData) {
//                            modSasteFineItemFragment.onModSasteEvent(0);
//                            modMsgFineItemFragment.onModMsgMidEvent(0);
//                            mInitModData = true;
//                        }
//                        setFineItemSoldoutListFull(mPresenter.getCurrentSlodoutFoodList_Full());
//                        showViewModeVisibility(MealConstant.fine_ViewMode);

                        showViewModeVisibility(MealConstant.food_group_ViewMode, MealConstant.food_ViewMode);
                        break;
                }

                mPresenter.filterSlodoutData(true);

                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    public void showModfierLayout(long fid) {
        if (!mInitModData) {
            modSasteFineItemFragment.loadModSasteData(0);
            modMsgFineItemFragment.loadModMsgData(0);
            mInitModData = true;
        }

        setFineItemSoldoutListFull(fid, mPresenter.getCurrentSlodoutFoodList_Full());
        showViewModeVisibility(MealConstant.fine_ViewMode);
    }

    public void showSoldoutNumberDialog(Long foodId, Long modifierId) {
        Long id = foodId != null ? foodId : modifierId;
        int type = foodId != null ? 2 : 3;
        //选择沽清的数量
        ChooseNumberDialog chooseNumberDialog = new ChooseNumberDialog(this);
//        chooseNumberDialog.setBackBtnText("暫停");
        chooseNumberDialog.builder();
        chooseNumberDialog.setOnClickListener(new ChooseNumberDialog.OnClickListener() {
            @Override
            public void onComfirmClick(String number) {
                if (Integer.parseInt(number) == 0) {
                    mPresenter.updateInvisible(id, type, 2);
                } else {
                    mPresenter.insertSoldoutCtrl(foodId, modifierId, Integer.parseInt(number), Integer.parseInt(number) == 0 ? 0 : 1, foodId != null ? 2 : 3);
                }
            }

            @Override
            public void onBackPage() {
                mPresenter.updateInvisible(id, type, 2);
            }
        });
        chooseNumberDialog.setType(2);
        chooseNumberDialog.setCancelable(true);
        chooseNumberDialog.show();
    }

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

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

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

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

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

    @Override
    public void setCurrentSoldoutFoodAdapter(DefaultAdapter adapter) {
        recycle_current_soldout_food.setAdapter(adapter);
    }

    @Override
    public void setFoodGroupAdapter(DefaultAdapter adapter) {
    }

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

    @Override
    public void setComboAdapter(DefaultAdapter adapter) {
        recycle_combo.setAdapter(adapter);
    }

    private GridLayoutManager foodRecycleLayoutManager;

    public void initFoodLayoutManager(int orientation) {
        foodRecycleLayoutManager = new GridLayoutManager(this, 1, orientation, false);
        recycle_food.setLayoutManager(foodRecycleLayoutManager);
        recycle_food.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    public RecyclerView getRecycleCurrentSoldoutFood() {
        return recycle_current_soldout_food;
    }

    @Override
    public RecyclerView getRecycleFoodGroup() {
        return recycle_food_group;
    }

    @Override
    public RecyclerView getRecycleFood() {
        return recycle_food;
    }

    @Override
    public void setFoodGroupRecycleSpanCount(int size) {

    }

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

    @Override
    public int getSoldoutType() {
        return mSoldoutType;
    }

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

    @Override
    public void initFineItemTabBarViewPage() {

    }

    @Override
    public void showFoodLayoutVisibility() {

    }

    @Override
    public void showFineItemLayoutVisibility() {

    }

    @Override
    public void showTvRestore(boolean show) {
        if (show) {
            tv_restore.setVisibility(View.VISIBLE);
            tv_soldout.setVisibility(View.GONE);
        } else {
            tv_restore.setVisibility(View.GONE);
            tv_soldout.setVisibility(View.VISIBLE);
        }
    }

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

    @Override
    public void onPageSizeChanged(int pageSize) {
    }

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

    private void initTabAndPager() {
        QMUIFragmentPagerAdapter pagerAdapter = new QMUIFragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public Fragment createFragment(int position) {
                switch (position) {
                    case 2:
                        if (modMsgFineItemFragment != null) {
                            return modMsgFineItemFragment;
                        }
                        modMsgFineItemFragment = FineItemAllFragment.newInstance();
                        return modMsgFineItemFragment;
                    case 1:
                        if (modSasteFineItemFragment != null) {
                            return modSasteFineItemFragment;
                        }
                        modSasteFineItemFragment = FineItemAllFragment.newInstance();
                        return modSasteFineItemFragment;
                    default:
                        if (oneselfFineItemFragment != null) {
                            return oneselfFineItemFragment;
                        }
                        oneselfFineItemFragment = FineItemOneselfFragment.newInstance();
                        return oneselfFineItemFragment;
                }
            }

            @Override
            public int getCount() {
                return mFineTabTitles.length;
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return "";
            }
        };

        QMUITabBuilder builder = mTabSegment.tabBuilder();
        QMUITab tab1 = builder
                .setText(mFineTabTitles[0])
                .build(mContext);
        QMUITab tab2 = builder
                .setText(mFineTabTitles[1])
                .build(mContext);
        QMUITab tab3 = builder
                .setText(mFineTabTitles[2])
                .build(mContext);
        mTabSegment
                .addTab(tab1)
                .addTab(tab2)
                .addTab(tab3);

        mContentViewPager.setAdapter(pagerAdapter);
        mContentViewPager.setCurrentItem(mCurrentFinePageIndex);
        mContentViewPager.setOffscreenPageLimit(2);
        int space = QMUIDisplayHelper.dp2px(this, 16);
        mTabSegment.setIndicator(new QMUITabIndicator(QMUIDisplayHelper.dp2px(this, 2), false, true));
        mTabSegment.setDefaultTextSize(QMUIDisplayHelper.dp2px(this, 16), QMUIDisplayHelper.dp2px(this, 16));
        mTabSegment.setPadding(space, 0, space, 0);
        mTabSegment.setupWithViewPager(mContentViewPager, false);
        mTabSegment.setOnTabClickListener(new QMUITabSegment.OnTabClickListener() {
            @Override
            public void onTabClick(int index) {
                mCurrentFinePageIndex = index;
            }
        });
        mTabSegment.addOnTabSelectedListener(new QMUITabSegment.OnTabSelectedListener() {

            @Override
            public void onTabSelected(int index) {
                mCurrentFinePageIndex = index;
            }

            @Override
            public void onTabUnselected(int index) {
            }

            @Override
            public void onTabReselected(int index) {
                LogUtil.d(TAG, "onTabReselected " + index);
            }

            @Override
            public void onDoubleTap(int index) {
                LogUtil.d(TAG, "onDoubleTap " + index);
            }
        });
    }

    public void setFineItemSoldoutListFull(Long fid, List<SoldoutCtrFood> currentSoldoutFoodListc_Full) {
        if (oneselfFineItemFragment != null) {
            oneselfFineItemFragment.loadComboData(fid);
            oneselfFineItemFragment.setSoldoutFoodList_Full(currentSoldoutFoodListc_Full);
            oneselfFineItemFragment.updateSoldoutFoodList_Full();
        }
        if (modMsgFineItemFragment != null) {
            modMsgFineItemFragment.loadModMsgData(0);
            modMsgFineItemFragment.setModifierSoldoutFoodList_Full(currentSoldoutFoodListc_Full);
            modMsgFineItemFragment.updateParentModifierSlodoutFoodList_Full();
        }
        if (modSasteFineItemFragment != null) {
            modSasteFineItemFragment.loadModSasteData(0);
            modSasteFineItemFragment.setModifierSoldoutFoodList_Full(currentSoldoutFoodListc_Full);
            modSasteFineItemFragment.updateParentModifierSlodoutFoodList_Full();
        }
        mPresenter.filterSlodoutData(false);
    }

    public FoodGroupAdapter getFoodGroupAdapter() {
        return mFoodGroupAdapter;
    }

    public SoldoutCtrlPresenter getSoldoutCtrlPresenter() {
        return mPresenter;
    }
}
