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.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.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;

    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_delete, R.id.topbar_right_delete_button).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                showDelete = !showDelete;
//                updateDeleteBtnState();
//            }
//        });
        topbarFoodIngredients.setTitle("類別管理");
        topbarFoodIngredients.addLeftBackImageButton().setOnClickListener(v -> killMyself());
    }

    /**
     * 修改刪除按鈕的顯示狀態
     */
    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, "類別名稱", "请輸入類別名稱", level != mPresenter.primaryCategoryTag);
            new XPopup.Builder(getContext())
                    .asCustom(categoryPopup.setListener(() -> {
                        //創建分類
                        if (TextUtil.isEmptyOrNullOrUndefined(categoryPopup.getEditText())) {
                            showMessage("請輸入分類名稱");
                            return;
                        }
                        //創建分類
                        mPresenter.addCategory(finalParentId, categoryPopup.getEditText().getText().toString(), finalLevel);
                    }, () -> {
                        //刪除分類
                        deleteCategory(finalLevel);
                    }))
                    .show();
        } else {
            showMessage("請選擇分類");
        }
    }

    private void deleteCategory(int finalLevel) {
        String categoryName = null;
        int categoryId = 0;
        int position = 0;
        if (finalLevel == mPresenter.secondCategoryTag) {
            CategoryBean categoryBean = baseCategoryAdapter.getData().get(baseCategoryAdapter.getSelectedIndex());
            categoryName = categoryBean.getCategoryName();
            categoryId = categoryBean.getId();
            position = baseCategoryAdapter.getSelectedIndex();
        } else if (finalLevel == mPresenter.thirdCategoryTag) {
            FoodCategoryResultBean.DataBean.FoodCategoryBean categoryBean1 = secondCategoryAdapter.getData().get(secondCategoryAdapter.getSelectIndex());
            categoryName = categoryBean1.getName();
            categoryId = categoryBean1.getId();
            position = secondCategoryAdapter.getSelectIndex();
        }
        //刪除該分類
        String finalCategoryName = categoryName;
        int finalCategoryId = categoryId;
        int finalPosition = position;
        new AppDialog().showWaringDialog(mContext, "是否確認刪除該類別【" + categoryName + "】,子類將一同刪除？", (view1, dialog1) -> {
            mPresenter.deleteFoodCategory(mPresenter.toFoodCategoryBean(0, finalCategoryName, finalCategoryId), mPresenter.primaryCategoryTag, finalPosition);
            dialog1.dismiss();
        });
    }

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

    @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));
                rvFirstCategory.setAdapter(baseCategoryAdapter);
                baseCategoryAdapter.setOnItemClickListener((adapter, view, 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(mPresenter.toFoodCategoryBean(0, categoryBean.getCategoryName(), categoryBean.getId()), mPresenter.primaryCategoryTag, position);
                            dialog.dismiss();
                        });
                    }
                });
            } else {
                baseCategoryAdapter.setList(data);
            }
        } 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);
                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) -> {
                            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 {
                secondCategoryAdapter.setSelectIndex(1);
                secondCategoryAdapter.setList(list);
            }
        } else if (hierarchy == mPresenter.thirdCategoryTag) {
            hideLoading();
            if (thirdCategoryAdapter == null) {
                thirdCategoryAdapter = new SecondCategoryAdapter(list);
                thirdCategoryAdapter.setSelectIndex(-1)
                        .setUnCheckedBg(ContextCompat.getDrawable(mContext, R.drawable.shape_color_da_stoke_fifteen_corners))
                        .setUnCheckedTextColor(ContextCompat.getColor(mContext, R.color.color_68));
                addOnDelete(thirdCategoryAdapter, "】？", mPresenter.thirdCategoryTag);
                rvThirdCategory.setLayoutManager(new GridLayoutManager(mContext, 3));
                rvThirdCategory.setAdapter(thirdCategoryAdapter);
            } else {
                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), 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();
    }
}
