package com.gingersoft.supply_chain.mvp.ui.fragment.category;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gingersoft.gsa.cloud.common.loadsir.purchase.EmptyCategoryCallback;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.ui.utils.AppDialog;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.R2;
import com.gingersoft.supply_chain.di.component.DaggerCategoryComponent;
import com.gingersoft.supply_chain.mvp.bean.OrderCategoryBean;
import com.gingersoft.supply_chain.mvp.content.PurchaseConstant;
import com.gingersoft.supply_chain.mvp.contract.CategoryContract;
import com.gingersoft.supply_chain.mvp.presenter.CategoryPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.FoodCategoryAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.gingersoft.supply_chain.mvp.ui.widget.NewAddCategoryPopup;
import com.jess.arms.di.component.AppComponent;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadSir;
import com.lxj.xpopup.XPopup;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.qmuiteam.qmui.widget.QMUITopBar;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.gingersoft.supply_chain.mvp.ui.fragment.category.CategorySelectFragment.SELECT_CATEGORY_DATA_KEY;
import static com.gingersoft.supply_chain.mvp.ui.fragment.category.CategorySelectFragment.SELECT_FOOD_CATEGORY_RESULT_CODE;


/**
 * ================================================
 * Description: 分類管理
 */
public class CategoryFragment extends BaseSupplyChainFragment<CategoryPresenter> implements CategoryContract.View, View.OnClickListener {

    @BindView(R2.id.topbar_food_ingredients)
    QMUITopBar topbarFoodIngredients;
    @BindView(R2.id.ed_category_search)
    EditText edCategorySearch;
    @BindView(R2.id.btn_category_search)
    QMUIAlphaButton btnCategorySearch;
    @BindView(R2.id.layout_category_search)
    LinearLayout layoutCategorySearch;
    @BindView(R2.id.btn_add_first_category)
    QMUIAlphaTextView btnAddFirstCategory;
    @BindView(R2.id.rv_first_category)
    RecyclerView rvFirstCategory;
    @BindView(R2.id.rv_second_category_title)
    TextView rvSecondCategoryTitle;
    @BindView(R2.id.rv_second_category)
    RecyclerView rvSecondCategory;
    @BindView(R2.id.rv_third_category)
    RecyclerView rvThirdCategory;
    @BindView(R2.id.card_second_category)
    CardView cardSecondCategory;
    @BindView(R2.id.layout_third_category)
    FrameLayout thirdCategoryLayout;
    @BindView(R2.id.tv_new_third_category)
    QMUIAlphaTextView addThirdCategory;
    @BindView(R2.id.tv_new_second_category)
    QMUIAlphaTextView addSecondCategory;
    @BindView(R2.id.layout_category)
    LinearLayout layoutCategory;
    @BindView(R2.id.layout_select_category_btn)
    LinearLayout layoutSelectBtn;
    @BindView(R2.id.layout_category_right)
    RelativeLayout layoutCategoryRight;
    @BindView(R2.id.layout_category_content)
    LinearLayout layoutCategoryContent;
    /**
     * 當前選中的是幾級分類
     */
    private int currentLevel;
    /**
     * 頁面是管理分類
     * 還是選擇分類 SELECT_CATEGORY
     */
    private int pageType;
    /**
     * 默認選中的分類
     */
    private String categoryName;
    /**
     * 默認分類的下標，一級、二級、三級
     */
    private int[] categoryPosition;


    public final static String PAGE_TYPE_KEY = "pageType";

    private final static String CATEGORY_NAME_KEY = "categoryNameKey";
    /**
     * pageType 為選擇分類
     */
    public final static int SELECT_CATEGORY = 1001;

    public static CategoryFragment newInstance(String categoryName, int pageType) {
        CategoryFragment fragment = new CategoryFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(PAGE_TYPE_KEY, pageType);
        bundle.putString(CATEGORY_NAME_KEY, categoryName);
        fragment.setArguments(bundle);
        return fragment;
    }

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

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerCategoryComponent //如找不到该类,请编译一下项目
                .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_category, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        loadService = LoadSir.getDefault().register(layoutCategoryContent, (Callback.OnReloadListener) v -> showAddCategory(getString(R.string.str_new_add_category), 0, mPresenter.primaryCategoryTag));
        Bundle arguments = getArguments();
        if (arguments != null) {
            pageType = arguments.getInt(PAGE_TYPE_KEY, 0);
            categoryName = arguments.getString(CATEGORY_NAME_KEY);
            //選擇分類
            layoutSelectBtn.setVisibility(pageType == SELECT_CATEGORY ? View.VISIBLE : View.GONE);
        }
        initTopBar();
        mPresenter.getCategoryTrees();
    }

    private void initTopBar() {
        topbarFoodIngredients.addRightImageButton(R.drawable.ic_white_edit, R.id.topbar_right_delete_button).setOnClickListener(v -> {
            FoodCategoryAdapter currentCategoryAdapter = getCurrentCategoryAdapter();
            OrderCategoryBean.FoodCategoryTrees categoryInfo = getCategoryInfo(currentCategoryAdapter);
            if (categoryInfo != null) {
                showEditCategoryPop(categoryInfo, currentCategoryAdapter.getSelectIndex());
            }
        });
        if (pageType == SELECT_CATEGORY) {
            topbarFoodIngredients.setTitle(getString(R.string.str_choice_category));
        } else {
            topbarFoodIngredients.setTitle(getString(R.string.str_category_manager));
        }
        topbarFoodIngredients.addLeftBackImageButton().setOnClickListener(v -> killMyself());
    }

    /**
     * 獲取當前選中的分類adapter
     */
    private FoodCategoryAdapter getCurrentCategoryAdapter() {
        if (currentLevel == mPresenter.primaryCategoryTag) {
            return categoryAdapter;
        } else if (currentLevel == mPresenter.secondCategoryTag) {
            return secondCategoryAdapter;
        } else if (currentLevel == mPresenter.thirdCategoryTag) {
            return thirdCategoryAdapter;
        } else {
            showMessage(getString(R.string.str_please_reselect_category));
            return null;
        }
    }

    /**
     * 顯示編輯分類彈窗
     *
     * @param foodCategoryTrees 分類信息
     * @param position          編輯的分類下標，編輯之後用於刷新
     */
    private void showEditCategoryPop(OrderCategoryBean.FoodCategoryTrees foodCategoryTrees, int position) {
        NewAddCategoryPopup categoryPopup = new NewAddCategoryPopup(mContext, getString(R.string.str_modify), getString(R.string.str_category_name), getString(R.string.str_please_modify_current_category_name), foodCategoryTrees.getName(), true);
        categoryPopup.setOnDeleteListener(v -> {
            //刪除分類
            AppDialog.getInstance().showWaringDialog(mContext, String.format(getString(R.string.str_delete_category_tip), foodCategoryTrees.getName()), () -> {
                categoryPopup.dismiss();
                mPresenter.deleteFoodCategory(foodCategoryTrees, currentLevel, position);
            });
        });
        categoryPopup.setListener(() -> {
            //修改分類
            if (TextUtil.isEmptyOrNullOrUndefined(categoryPopup.getEditText())) {
                showMessage(getString(R.string.str_please_input_category_name));
                return;
            }
            mPresenter.updateFoodCategory(mPresenter.toFoodCategoryBean(foodCategoryTrees.getParentId(), TextUtil.getNotNullStrAndTrim(categoryPopup.getEditText().getText().toString()), foodCategoryTrees.getId()), currentLevel, position);
        }, ()->{});
        AppDialog.getInstance().showCustomPop(requireContext(), categoryPopup);
    }

    /**
     * 獲取當前分類信息
     *
     * @param categoryAdapter 分類adapter
     * @return 分類信息
     */
    private OrderCategoryBean.FoodCategoryTrees getCategoryInfo(FoodCategoryAdapter categoryAdapter) {
        if (categoryAdapter == null || categoryAdapter.getSelectIndex() == -1) {
            showMessage(getString(R.string.str_please_choise_category));
            return null;
        }
        if (categoryAdapter.getItemCount() > categoryAdapter.getSelectIndex()) {
            return categoryAdapter.getItem(categoryAdapter.getSelectIndex());
        }
        return null;
    }

    @OnClick({R2.id.btn_category_search, R2.id.tv_new_second_category, R2.id.btn_add_first_category, R2.id.tv_new_third_category, R2.id.btn_food_ingredients_confirm, R2.id.btn_food_ingredients_cancel})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.btn_food_ingredients_confirm) {
            //確定
            OrderCategoryBean.FoodCategoryTrees categoryInfo = getCategoryInfo(getCurrentCategoryAdapter());
            if (categoryInfo != null) {
                Bundle bundle = new Bundle();
                List<OrderCategoryBean.FoodCategoryTrees> selectCategory = new ArrayList<>();
                selectCategory.add(categoryInfo);
                bundle.putSerializable(SELECT_CATEGORY_DATA_KEY, (Serializable) selectCategory);
                setFragmentResult(SELECT_FOOD_CATEGORY_RESULT_CODE, bundle);
                killMyself();
            }
        } else if (viewId == R.id.btn_food_ingredients_cancel) {
            //取消
            killMyself();
        } else {
            //新增一級、二級、三級分類
            String parentCategoryName = null;
            int level = 0;
            int parentId = 0;
            if (viewId == R.id.btn_add_first_category) {
                //添加一級分類
                //沒有父級數據，直接添加
                parentCategoryName = getString(R.string.str_new_add_category);
                parentId = 0;
                level = mPresenter.primaryCategoryTag;
            } else if (viewId == R.id.tv_new_second_category) {
                //添加二級分類
                //拿到選中的一級分類信息
                OrderCategoryBean.FoodCategoryTrees foodCategoryTrees = categoryAdapter.getItem(categoryAdapter.getSelectIndex());
                parentCategoryName = foodCategoryTrees.getName();
                parentId = foodCategoryTrees.getId();
                level = mPresenter.secondCategoryTag;
            } else if (viewId == R.id.tv_new_third_category) {
                //添加三級分類
                //拿到選中的二級分類信息
                OrderCategoryBean.FoodCategoryTrees item = secondCategoryAdapter.getItem(secondCategoryAdapter.getSelectIndex());
                parentCategoryName = item.getName();
                parentId = item.getId();
                level = mPresenter.thirdCategoryTag;
            }
            showAddCategory(parentCategoryName, parentId, level);
        }
    }

    /**
     * 顯示添加分類彈窗
     *
     * @param parentCategoryName 父分類名稱
     * @param parentId           父分類id
     * @param level              添加的是幾級分類
     */
    private void showAddCategory(String parentCategoryName, int parentId, int level) {
        if (TextUtil.isNotEmptyOrNullOrUndefined(parentCategoryName)) {
            NewAddCategoryPopup categoryPopup = new NewAddCategoryPopup(mContext, parentCategoryName, getString(R.string.str_category_name), getString(R.string.str_please_input_category_name), null, false);
            new XPopup.Builder(getContext())
                    .asCustom(categoryPopup.setListener(() -> {
                        //創建分類
                        if (TextUtil.isEmptyOrNullOrUndefined(categoryPopup.getEditText())) {
                            showMessage(getString(R.string.str_please_input_category_name));
                            return;
                        }
                        //創建分類
                        mPresenter.addCategory(parentId, TextUtil.getNotNullStrAndTrim(categoryPopup.getEditText().getText().toString()), level);
                    }, () -> {
                    }))
                    .show();
        } else {
            showMessage(getString(R.string.str_please_choise_category));
        }
    }

    //一級
    private FoodCategoryAdapter categoryAdapter;
    //二級
    private FoodCategoryAdapter secondCategoryAdapter;
    //三級
    private FoodCategoryAdapter thirdCategoryAdapter;

    /**
     * 設置了到時候用於編輯或刪除
     *
     * @param level 當前選中的是第幾級分類
     */
    private void setCurrentInfo(int level) {
        currentLevel = level;
    }

    @Override
    public void loadCategoryInfo(List<OrderCategoryBean.FoodCategoryTrees> data) {
        if (TextUtil.isNotEmptyOrNullOrUndefined(categoryName)) {
            categoryPosition = mPresenter.getCategoryIndexByName(categoryName, data);
        } else {
            categoryPosition = new int[]{0, 0, 0};
        }
        //加載一級分類
        if (categoryAdapter == null) {
            categoryAdapter = new FoodCategoryAdapter(R.layout.item_first_category, data)
                    .setUnCheckedBg(R.color.trans)
                    .setCheckedBg(R.drawable.shape_left_radio_shadow)
                    .setUnCheckedTextColor(ContextCompat.getColor(mContext, R.color.color_3c))
                    .setCheckedTextColor(ContextCompat.getColor(mContext, R.color.theme_color));
            rvFirstCategory.setAdapter(categoryAdapter);
            //設置當前選中一級分類
            setCurrentInfo(mPresenter.primaryCategoryTag);
            categoryAdapter.setOnItemClickListener((adapter, view, position) -> {
                //分類點擊事件
                //設置當前選中一級分類。一級分類的第position個分類
                setCurrentInfo(mPresenter.primaryCategoryTag);
                //修改默認選中
                categoryAdapter.setSelectIndex(position);
                //刷新二級分類
                loadSecondCategory(categoryAdapter.getItem(position).getFoodCategoryTrees());
            });
        } else {
            categoryAdapter.setNewInstance(data);
            setCurrentInfo(mPresenter.primaryCategoryTag);
        }
        setSecondCategoryVisibility();
        if (categoryAdapter.getItemCount() > 0) {
            int defaultSelect = categoryPosition[0];
            //如果有一級分類，默認顯示第一個一級分類下的二級分類
            categoryAdapter.setSelectIndex(defaultSelect);
            loadSecondCategory(categoryAdapter.getItem(defaultSelect).getFoodCategoryTrees());
            //顯示新增二級分類
            addSecondCategory.setVisibility(View.VISIBLE);
        } else {
            categoryAdapter.setSelectIndex(-1);
        }
    }

    /**
     * 加載二級分類
     *
     * @param data 分類數據
     */
    @Override
    public void loadSecondCategory(List<OrderCategoryBean.FoodCategoryTrees> data) {
        //加載二級時，並沒有默認選中二級，所以這時候三級不展示
        //顯示新增二級分類按鈕
        addSecondCategory.setVisibility(View.VISIBLE);
        //隱藏新增三級分類按鈕
        addThirdCategory.setVisibility(View.GONE);
        //隱藏三級分類
        if (thirdCategoryAdapter != null) {
            thirdCategoryAdapter.setNewInstance(null);
        } else {
            rvThirdCategory.setVisibility(View.GONE);
        }
        //判斷是否需要給二級分類添加一個"新增類別"按鈕
        addNewAddBtn(data);
        //加載二級分類adapter
        if (secondCategoryAdapter == null) {
            secondCategoryAdapter = new FoodCategoryAdapter(data);
            //因為第一個數據是空的，用來顯示按鈕，所以下標跳過0，默認選中1
            //設置adapter的信息
            secondCategoryAdapter.setCheckedBg(R.drawable.shape_app_btn_small_radius)
                    .setUnCheckedBg(R.drawable.shape_five_radius_gray_stroke)
                    .setCheckedTextColor(ContextCompat.getColor(mContext, R.color.white))
                    .setUnCheckedTextColor(ContextCompat.getColor(mContext, R.color.color_3c))
                    .setSelectIndex(categoryPosition[1] + 1)
                    .setOnItemClickListener((adapter, view, position) -> {
                        //二級分類點擊事件，設置當前數據為二級分類
                        setCurrentInfo(mPresenter.secondCategoryTag);
                        secondCategoryAdapter.setSelectIndex(position);
                        setSecondCategoryVisibility();
                        //加載三級分類
                        loadThirdCategory(secondCategoryAdapter.getItem(position).getFoodCategoryTrees());
                    });
            rvSecondCategory.setLayoutManager(new GridLayoutManager(mContext, 3) {
                @Override
                public boolean canScrollHorizontally() {
                    return true;
                }
            });
            rvSecondCategory.setAdapter(secondCategoryAdapter);
            if (secondCategoryAdapter.getItemCount() > 0) {
                if (secondCategoryAdapter.getSelectIndex() < secondCategoryAdapter.getItemCount()) {
                    //二級分類點擊事件，設置當前數據為二級分類
                    setCurrentInfo(mPresenter.secondCategoryTag);
                    loadThirdCategory(secondCategoryAdapter.getItem(secondCategoryAdapter.getSelectIndex()).getFoodCategoryTrees());
                }
            }
        } else {
            //重置選中
            secondCategoryAdapter.setSelectIndex(-1);
            secondCategoryAdapter.setNewInstance(data);
            secondCategoryAdapter.notifyDataSetChanged();
        }
        setThirdCategoryVisibility();
    }

    private void setSecondCategoryVisibility() {
        cardSecondCategory.setVisibility(categoryAdapter.getItemCount() > 0 ? View.VISIBLE : View.GONE);
        setThirdCategoryVisibility();
        if (cardSecondCategory.getVisibility() == View.GONE) {
            loadService.showCallback(EmptyCategoryCallback.class);
        } else {
            loadService.showSuccess();
        }
    }

    private void setThirdCategoryVisibility() {
        if (secondCategoryAdapter != null && secondCategoryAdapter.getItemCount() > 1 && secondCategoryAdapter.getSelectIndex() > 0) {
            thirdCategoryLayout.setVisibility(View.VISIBLE);
        } else {
            thirdCategoryLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 加載三級分類
     *
     * @param data
     */
    @Override
    public void loadThirdCategory(List<OrderCategoryBean.FoodCategoryTrees> data) {
        //顯示新增三級分類按鈕
        addThirdCategory.setVisibility(View.VISIBLE);
        rvThirdCategory.setVisibility(View.VISIBLE);
        //第一個位置是新增類別按鈕
        addNewAddBtn(data);
        if (thirdCategoryAdapter == null) {
            thirdCategoryAdapter = new FoodCategoryAdapter(data);
            thirdCategoryAdapter.setSelectIndex(categoryPosition[2] + 1)
                    .setCheckedBg(R.drawable.shape_color_theme_stoke_fifteen_corners)
                    .setUnCheckedBg(R.drawable.shape_color_da_stoke_fifteen_corners)
                    .setCheckedTextColor(ContextCompat.getColor(mContext, R.color.white))
                    .setUnCheckedTextColor(ContextCompat.getColor(mContext, R.color.color_68))
                    .setOnItemClickListener((adapter, view, position) -> {
                        setCurrentInfo(mPresenter.thirdCategoryTag);
                        thirdCategoryAdapter.setSelectIndex(position);
                    });
            if (thirdCategoryAdapter.getItemCount() > thirdCategoryAdapter.getSelectIndex()) {
                //二級分類點擊事件，設置當前數據為二級分類
                setCurrentInfo(mPresenter.thirdCategoryTag);
            }
            rvThirdCategory.setLayoutManager(new GridLayoutManager(mContext, 3));
            rvThirdCategory.setAdapter(thirdCategoryAdapter);
        } else {
            //重置選中
            thirdCategoryAdapter.setSelectIndex(-1);
            thirdCategoryAdapter.setNewInstance(data);
        }
    }

    /**
     * 添加分類成功後的回調
     *
     * @param categoryTrees 分類信息
     * @param hierarchy     新增的是第幾級分類
     */
    @Override
    public void addCategory(OrderCategoryBean.FoodCategoryTrees categoryTrees, int hierarchy) {
        if (hierarchy == mPresenter.primaryCategoryTag) {
            //添加到尾部
            categoryAdapter.addData(categoryAdapter.getItemCount(), categoryTrees);
            int clickIndex = categoryAdapter.getItemCount() - 1;
            //滑動到尾部去
            rvFirstCategory.scrollToPosition(clickIndex);
            //設置為選中
            categoryAdapter.setSelectIndex(clickIndex);
            //調用點擊事件，刷新下面的二級分類
            categoryAdapter.getOnItemClickListener().onItemClick(categoryAdapter, null, clickIndex);
            setSecondCategoryVisibility();
        } else if (hierarchy == mPresenter.secondCategoryTag) {
            //如果是添加的二級分類，就要拿到當前的一級分類，給一級分類的子分類集合中添加分類
            newCategory(categoryTrees, categoryAdapter);
            setThirdCategoryVisibility();
        } else if (hierarchy == mPresenter.thirdCategoryTag) {
            //如果是添加的二級分類，就要拿到當前的一級分類，給一級分類的子分類集合中添加分類
            newCategory(categoryTrees, secondCategoryAdapter);
        }
    }

    /**
     * 新增分類
     *
     * @param categoryTrees 分類
     * @param adapter       父分類adapter
     */
    public void newCategory(OrderCategoryBean.FoodCategoryTrees categoryTrees, FoodCategoryAdapter adapter) {
        OrderCategoryBean.FoodCategoryTrees item = adapter.getItem(adapter.getSelectIndex());
        List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees = item.getFoodCategoryTrees();
        if (foodCategoryTrees == null) {
            foodCategoryTrees = new ArrayList<>();
            foodCategoryTrees.add(0, new OrderCategoryBean.FoodCategoryTrees(-1));
        }
        foodCategoryTrees.add(categoryTrees);
        item.setFoodCategoryTrees(foodCategoryTrees);
        //調用點擊事件，刷新下面的二級分類
        OnItemClickListener onItemClickListener = adapter.getOnItemClickListener();
        if (onItemClickListener != null) {
            onItemClickListener.onItemClick(adapter, null, adapter.getSelectIndex());
        }
    }


    /**
     * @param type         操作類型：刪除或修改  Constant.DELETE  Constant.UPDATE
     * @param hierarchy    第幾級分類
     * @param categoryName 分類名稱
     * @param position     分類下標
     */
    @Override
    public void updateCategory(int type, int hierarchy, String categoryName, int position) {
        if (hierarchy == mPresenter.primaryCategoryTag && categoryAdapter != null) {
            if (type == PurchaseConstant.DELETE) {
                //如果是刪除，就移除掉
                categoryAdapter.removeAt(position);
                if (categoryAdapter.getItemCount() > 0) {
                    // 總數量大於0，選中第0個
                    rvFirstCategory.scrollToPosition(0);
                    categoryAdapter.getOnItemClickListener().onItemClick(categoryAdapter, null, 0);
                } else {
                    //沒有一級分類了
                    //清除二級三級分類
                    secondCategoryAdapter.setList(null);
                    thirdCategoryAdapter.setList(null);
                    setSecondCategoryVisibility();
                }
            } else if (type == PurchaseConstant.UPDATE) {
                //修改了分類名稱，拿到對應數據刷新
                OrderCategoryBean.FoodCategoryTrees item = categoryAdapter.getItem(position);
                item.setName(categoryName);
                categoryAdapter.notifyItemChanged(position);
            }
        } else if (hierarchy == mPresenter.secondCategoryTag && secondCategoryAdapter != null) {
            updateChildCategory(secondCategoryAdapter, type, hierarchy, categoryName, position);
        } else if (hierarchy == mPresenter.thirdCategoryTag && thirdCategoryAdapter != null) {
            updateChildCategory(thirdCategoryAdapter, type, hierarchy, categoryName, position);
        }
    }

    @Override
    public void onError() {
//        loadService.showCallback(ErrorCallback.class);
    }

    /**
     * 修改二級、三級分類
     *
     * @param adapter      適配器
     * @param type         操作類型：刪除還是修改
     * @param hierarchy    分類級別
     * @param categoryName 分類名稱
     * @param position     分類下標
     */
    private void updateChildCategory(FoodCategoryAdapter adapter, int type, int hierarchy, String categoryName, int position) {
        if (type == PurchaseConstant.DELETE) {
            adapter.removeAt(position);
            //這裡之所以刷新所有，是為了重新刷新高度
            adapter.notifyDataSetChanged();
            if (hierarchy == mPresenter.secondCategoryTag) {
                thirdCategoryAdapter.setNewInstance(null);
                //如果是二級分類，還需要判斷如果分類數量為0時，就不顯示三級分類
                if (secondCategoryAdapter.getItemCount() <= 1) {
                    setThirdCategoryVisibility();
                    //切換選中一級
                    setCurrentInfo(mPresenter.primaryCategoryTag);
                } else {
                    adapter.getOnItemClickListener().onItemClick(adapter, null, 1);
                }
            } else {
                //刪除的是三級，切換選中到二級
                setCurrentInfo(mPresenter.secondCategoryTag);
            }
        } else if (type == PurchaseConstant.UPDATE) {
            //修改了分類名稱
            OrderCategoryBean.FoodCategoryTrees item = adapter.getItem(position);
            item.setName(categoryName);
            adapter.notifyItemChanged(position);
        }
    }

    /**
     * 添加新增按鈕
     */
    private void addNewAddBtn(List<OrderCategoryBean.FoodCategoryTrees> data) {
        if (data != null && data.size() > 0) {
            if (data.get(0).getId() != -1) {
                OrderCategoryBean.FoodCategoryTrees foodCategoryTrees = new OrderCategoryBean.FoodCategoryTrees();
                foodCategoryTrees.setId(-1);
                data.add(0, foodCategoryTrees);
            }
        } else {
            data = new ArrayList<>();
            OrderCategoryBean.FoodCategoryTrees foodCategoryTrees = new OrderCategoryBean.FoodCategoryTrees();
            foodCategoryTrees.setId(-1);
            data.add(0, foodCategoryTrees);
        }
    }
}
