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

import android.app.Dialog;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
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.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gingersoft.gsa.cloud.common.loadsir.EmptyCallback;
import com.gingersoft.gsa.cloud.common.loadsir.ErrorCallback;
import com.gingersoft.gsa.cloud.common.utils.inputFilter.InputFilterUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.common.utils.toast.ToastUtils;
import com.gingersoft.gsa.cloud.ui.adapter.BaseCategoryAdapter;
import com.gingersoft.gsa.cloud.ui.bean.view.CategoryBean;
import com.gingersoft.gsa.cloud.ui.utils.AppDialog;
import com.gingersoft.gsa.cloud.ui.utils.DialogUtils;
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.FoodCategoryResultBean;
import com.gingersoft.supply_chain.mvp.contract.CategoryContract;
import com.gingersoft.supply_chain.mvp.presenter.CategoryPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.SecondCategoryAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.gingersoft.supply_chain.mvp.ui.widget.CategoryPopup;
import com.jess.arms.base.App;
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.lxj.xpopup.enums.PopupPosition;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.qmuiteam.qmui.widget.QMUITopBar;

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

import butterknife.BindView;
import butterknife.OnClick;


/**
 * ================================================
 * 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.tv_new_third_category)
    QMUIAlphaTextView addThirdCategory;
    @BindView(R2.id.layout_category)
    LinearLayout layoutCategory;
    /**
     * 是否顯示刪除
     */
    private boolean showDelete = false;

    /**
     * 當前選中的是幾級分類
     */
    private int currentLevel;
    /**
     * 當前等級分類的下標
     */
    private int currentLevelPosition;

    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(layoutCategory, (Callback.OnReloadListener) v -> mPresenter.getFoodCategoryList("", 0, mPresenter.primaryCategoryTag));
        initTopBar();
        //先獲取一級分類
        mPresenter.getFoodCategoryList("", 0, mPresenter.primaryCategoryTag);
    }

    private void initTopBar() {
        topbarFoodIngredients.addRightImageButton(R.drawable.ic_white_edit, R.id.topbar_right_delete_button).setOnClickListener(v -> editCategory());
        topbarFoodIngredients.setTitle("類別管理");
        topbarFoodIngredients.addLeftBackImageButton().setOnClickListener(v -> killMyself());
    }

    /**
     * 右上角編輯分類
     */
    private void editCategory() {
        String categoryName = null;
        int categoryId = 0;
        int parentId = 0;
        if (currentLevel == mPresenter.primaryCategoryTag) {
            //如果是修改一級分類，拿到當前選中的分類的名稱，父級id，分類id
            if (baseCategoryAdapter != null) {
                List<CategoryBean> data = baseCategoryAdapter.getData();
                if (data.size() > currentLevelPosition) {
                    categoryName = data.get(currentLevelPosition).getCategoryName();
                    categoryId = data.get(currentLevelPosition).getId();
                }
            }
        } else if (currentLevel == mPresenter.secondCategoryTag) {
            //如果是修改二級分類，拿到當前選中的分類的名稱，父級id，分類id
            if (secondCategoryAdapter != null) {
                List<FoodCategoryResultBean.DataBean.FoodCategoryBean> secondData = secondCategoryAdapter.getData();
                if (secondData.size() > currentLevelPosition) {
                    categoryName = secondData.get(currentLevelPosition).getName();
                    categoryId = secondData.get(currentLevelPosition).getId();
                    parentId = secondData.get(currentLevelPosition).getParentId();
                }
            }
        } else if (currentLevel == mPresenter.thirdCategoryTag) {
            //如果是修改三級分類，拿到當前選中的分類的名稱，父級id，分類id
            if (secondCategoryAdapter != null) {
                List<FoodCategoryResultBean.DataBean.FoodCategoryBean> thirdData = thirdCategoryAdapter.getData();
                if (thirdData.size() > currentLevelPosition) {
                    categoryName = thirdData.get(currentLevelPosition).getName();
                    categoryId = thirdData.get(currentLevelPosition).getId();
                    parentId = thirdData.get(currentLevelPosition).getParentId();
                }
            }
        } else {
            showMessage("請選擇分類");
            return;
        }
        if (categoryId == 0) {
            showMessage("請重新選擇分類");
            return;
        }
        String finalCategoryName = categoryName;
        int finalCategoryId = categoryId;
        int finalParentId = parentId;

        CategoryPopup categoryPopup = new CategoryPopup(mContext, "修改", "類別名稱", "请修改當前類別名稱", categoryName, true);
        categoryPopup.setOnDeleteListener(v -> {
            //刪除分類
            AppDialog.getInstance().showWaringDialog(mContext, "是否確認刪除該類別【" + finalCategoryName + "】，子類將一同刪除？", (view, dialog) -> {
                categoryPopup.dismiss();
                dialog.dismiss();
                mPresenter.deleteFoodCategory(finalCategoryId, currentLevel, currentLevelPosition);
            });
        });
        new XPopup.Builder(getContext())
                .asCustom(categoryPopup.setListener(() -> {
                    //修改分類
                    if (TextUtil.isEmptyOrNullOrUndefined(categoryPopup.getEditText())) {
                        showMessage("請輸入分類名稱");
                        return;
                    }
                    mPresenter.updateFoodCategory(mPresenter.toFoodCategoryBean(finalParentId, finalCategoryName, finalCategoryId), currentLevel, currentLevelPosition);
                }, () -> {
                }))
                .show();
    }

    /**
     * 修改刪除按鈕的顯示狀態
     */
    private void updateDeleteBtnState() {
        if (baseCategoryAdapter != null) {
            baseCategoryAdapter.setShowDelete(showDelete);
        }
        if (secondCategoryAdapter != null) {
            secondCategoryAdapter.setShowDelete(showDelete);
        }
        if (thirdCategoryAdapter != null) {
            thirdCategoryAdapter.setShowDelete(showDelete);
        }
    }

    @OnClick({R2.id.btn_category_search, R2.id.tv_new_second_category, R2.id.btn_add_first_category, R2.id.tv_new_third_category})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        String parentCategoryName = null;
        int level = 0;
        int parentId = 0;
        if (viewId == R.id.btn_add_first_category) {
            //添加一級分類
            //沒有父級數據，直接添加
            parentCategoryName = "新增類別";
            parentId = 0;
            level = mPresenter.primaryCategoryTag;
        } else if (viewId == R.id.tv_new_second_category) {
            //添加二級分類
            if (baseCategoryAdapter != null) {
                List<CategoryBean> data = baseCategoryAdapter.getData();
                if (data.size() > baseCategoryAdapter.getSelectedIndex()) {
                    CategoryBean categoryBean = data.get(baseCategoryAdapter.getSelectedIndex());
                    parentCategoryName = categoryBean.getCategoryName();
                    parentId = categoryBean.getId();
                    level = mPresenter.secondCategoryTag;
                }
            }
        } else if (viewId == R.id.tv_new_third_category) {
            //添加三級分類
            if (secondCategoryAdapter != null) {
                FoodCategoryResultBean.DataBean.FoodCategoryBean selectData = secondCategoryAdapter.getSelectData();
                parentCategoryName = selectData.getName();
                parentId = selectData.getId();
                level = mPresenter.thirdCategoryTag;
            }
        }
        int finalParentId = parentId;
        int finalLevel = level;
        if (TextUtil.isNotEmptyOrNullOrUndefined(parentCategoryName)) {
            CategoryPopup categoryPopup = new CategoryPopup(mContext, parentCategoryName, "類別名稱", "请輸入類別名稱", null, false);
            new XPopup.Builder(getContext())
                    .asCustom(categoryPopup.setListener(() -> {
                        //創建分類
                        if (TextUtil.isEmptyOrNullOrUndefined(categoryPopup.getEditText())) {
                            showMessage("請輸入分類名稱");
                            return;
                        }
                        //創建分類
                        mPresenter.addCategory(finalParentId, categoryPopup.getEditText().getText().toString(), finalLevel);
                    }, () -> {
                    }))
                    .show();
        } else {
            showMessage("請選擇分類");
        }
    }

    //一級
    private BaseCategoryAdapter baseCategoryAdapter;
    //二級
    private SecondCategoryAdapter secondCategoryAdapter;
    //三級
    private SecondCategoryAdapter thirdCategoryAdapter;

    private void setCurrentInfo(int level, int position) {
        currentLevelPosition = position;
        currentLevel = level;
    }

    @Override
    public void loadCategoryInfo(List<FoodCategoryResultBean.DataBean.FoodCategoryBean> list, int hierarchy) {
        loadService.showSuccess();
        if (hierarchy == mPresenter.primaryCategoryTag) {
            List<CategoryBean> data = new ArrayList<>();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {
                    data.add(new CategoryBean(list.get(i).getId(), list.get(i).getName()));
                }
                if (data.size() > 0) {
                    mPresenter.getCategoryBeansById(data.get(0).getId(), mPresenter.secondCategoryTag);
                    if (baseCategoryAdapter != null) {
                        baseCategoryAdapter.setSelectedIndex(0);
                    }
                } else {
                    hideLoading();
                }
            } else {
                mPresenter.getCategoryBeansById(-1, mPresenter.secondCategoryTag);
            }
            if (baseCategoryAdapter == null) {
                baseCategoryAdapter = new BaseCategoryAdapter(data, mContext)
                        .setUnSelectColor(ContextCompat.getColor(mContext, R.color.color_3c))
                        .setSelectColor(ContextCompat.getColor(mContext, R.color.theme_color));
                setCurrentInfo(mPresenter.primaryCategoryTag, 0);

                rvFirstCategory.setAdapter(baseCategoryAdapter);
                baseCategoryAdapter.setOnItemClickListener((adapter, view, position) -> {
                    setCurrentInfo(mPresenter.primaryCategoryTag, position);

                    baseCategoryAdapter.setSelectedIndex(position);
                    List<CategoryBean> categoryBeans = baseCategoryAdapter.getData();
                    mPresenter.getCategoryBeansById(categoryBeans.get(position).getId(), mPresenter.secondCategoryTag);
                });
                baseCategoryAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                    if (view.getId() == R.id.iv_category_delete) {
                        //刪除該分類
                        CategoryBean categoryBean = baseCategoryAdapter.getData().get(position);
                        new AppDialog().showWaringDialog(mContext, "是否確認刪除該類別【" + categoryBean.getCategoryName() + "】,子類將一同刪除？", (view1, dialog) -> {
                            mPresenter.deleteFoodCategory(categoryBean.getId(), mPresenter.primaryCategoryTag, position);
                            dialog.dismiss();
                        });
                    }
                });
            } else {
                baseCategoryAdapter.setList(data);
                setCurrentInfo(mPresenter.primaryCategoryTag, 0);
            }
        } else if (hierarchy == mPresenter.secondCategoryTag) {
            if (list == null || list.size() <= 0) {
                addThirdCategory.setVisibility(View.GONE);
                mPresenter.getCategoryBeansById(-1, mPresenter.thirdCategoryTag);
            } else {
                //因為第一個是按鈕，沒有id
                addThirdCategory.setVisibility(View.VISIBLE);
                mPresenter.getCategoryBeansById(list.get(1).getId(), mPresenter.thirdCategoryTag);
            }
            //二級分類
            if (secondCategoryAdapter == null) {
                secondCategoryAdapter = new SecondCategoryAdapter(list);
                //因為第一個數據是空的，用來顯示按鈕，所以下標跳過0
                secondCategoryAdapter.setSelectIndex(1);
                setCurrentInfo(mPresenter.secondCategoryTag, 1);

                secondCategoryAdapter.setCheckedBg(ContextCompat.getDrawable(mContext, R.drawable.shape_app_btn_small_radius))
                        .setUnCheckedBg(ContextCompat.getDrawable(mContext, R.drawable.shape_five_radius_gray_stroke))
                        .setCheckedTextColor(ContextCompat.getColor(mContext, R.color.white))
                        .setUnCheckedTextColor(ContextCompat.getColor(mContext, R.color.color_3c))
                        .setOnItemClickListener((adapter, view, position) -> {
                            setCurrentInfo(mPresenter.secondCategoryTag, position);

                            secondCategoryAdapter.setSelectIndex(position);
                            List<FoodCategoryResultBean.DataBean.FoodCategoryBean> categoryBeans = secondCategoryAdapter.getData();
                            mPresenter.getCategoryBeansById(categoryBeans.get(position).getId(), mPresenter.thirdCategoryTag);
                        });
                addOnDelete(secondCategoryAdapter, "】,子類將一同刪除？", mPresenter.secondCategoryTag);
                rvSecondCategory.setLayoutManager(new GridLayoutManager(mContext, 3) {
                    @Override
                    public boolean canScrollHorizontally() {
                        return true;
                    }
                });
                rvSecondCategory.setAdapter(secondCategoryAdapter);
            } else {
                setCurrentInfo(mPresenter.secondCategoryTag, 1);
                secondCategoryAdapter.setSelectIndex(1);
                secondCategoryAdapter.setList(list);
            }
        } else if (hierarchy == mPresenter.thirdCategoryTag) {
            hideLoading();
            if (thirdCategoryAdapter == null) {
                thirdCategoryAdapter = new SecondCategoryAdapter(list);
                setCurrentInfo(mPresenter.thirdCategoryTag, 1);

                thirdCategoryAdapter.setSelectIndex(1)
                        .setCheckedBg(ContextCompat.getDrawable(mContext, R.drawable.shape_color_theme_stoke_fifteen_corners))
                        .setUnCheckedBg(ContextCompat.getDrawable(mContext, 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, position);
                            thirdCategoryAdapter.setSelectIndex(position);
                        });
                addOnDelete(thirdCategoryAdapter, "】？", mPresenter.thirdCategoryTag);
                rvThirdCategory.setLayoutManager(new GridLayoutManager(mContext, 3));
                rvThirdCategory.setAdapter(thirdCategoryAdapter);
            } else {
                setCurrentInfo(mPresenter.thirdCategoryTag, 1);
                thirdCategoryAdapter.setSelectIndex(1);
                thirdCategoryAdapter.setList(list);
            }
        }

    }

    private void addOnDelete(SecondCategoryAdapter categoryAdapter, String s, int categoryLevel) {
        categoryAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.iv_category_delete) {
                //刪除該分類
                new AppDialog().showWaringDialog(mContext, "是否確認刪除該類別【" + categoryAdapter.getData().get(position).getName() + s, (view1, dialog) -> {
                    mPresenter.deleteFoodCategory(categoryAdapter.getData().get(position).getId(), categoryLevel, position);
                    dialog.dismiss();
                });
            }
        });
    }

    @Override
    public void refreshInfo(int hierarchy, int position) {
        showDelete = false;
        updateDeleteBtnState();
        if (hierarchy == mPresenter.primaryCategoryTag && baseCategoryAdapter != null) {
            baseCategoryAdapter.removeAt(position);
            if (baseCategoryAdapter.getItemCount() > 0) {
                if (position - 1 < 0) {
                    position = 0;
                } else {
                    position -= 1;
                }
                baseCategoryAdapter.setSelectedIndex(position);
                baseCategoryAdapter.getOnItemClickListener().onItemClick(baseCategoryAdapter, rvFirstCategory.getChildAt(position), position);
            }
        } else if (hierarchy == mPresenter.secondCategoryTag && secondCategoryAdapter != null) {
            notifyAdapter(position, secondCategoryAdapter);
        } else if (hierarchy == mPresenter.thirdCategoryTag && thirdCategoryAdapter != null) {
            notifyAdapter(position, thirdCategoryAdapter);
        }

    }

    @Override
    public void loadCategoryFail() {
        loadService.showCallback(EmptyCallback.class);
    }

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

    private void notifyAdapter(int position, SecondCategoryAdapter categoryAdapter) {
        categoryAdapter.removeAt(position);
        if (categoryAdapter.getItemCount() > 0) {
            if (position - 1 < 1) {
                position = 1;
            } else {
                position -= 1;
            }
            categoryAdapter.setSelectIndex(position);
            categoryAdapter.getOnItemClickListener().onItemClick(categoryAdapter, null, position);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //獲取種類時，會連調幾次獲取下一級的接口，為了避免一直閃loading，不會關閉loading框，有時候會導致頁面關閉後還顯示loading
        //所以在這裡處理一下
        hideLoading();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            //獲取種類時，會連調幾次獲取下一級的接口，為了避免一直閃loading，不會關閉loading框，有時候會導致頁面關閉後還顯示loading
            //所以在這裡處理一下
            hideLoading();
        }
    }
}
