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.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.jess.arms.di.component.AppComponent;
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;
    /**
     * 是否顯示刪除
     */
    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) {
        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;
                if (baseCategoryAdapter != null) {
                    baseCategoryAdapter.setShowDelete(showDelete);
                }
                if (secondCategoryAdapter != null) {
                    secondCategoryAdapter.setShowDelete(showDelete);
                }
                if (thirdCategoryAdapter != null) {
                    thirdCategoryAdapter.setShowDelete(showDelete);
                }
            }
        });
        topbarFoodIngredients.setTitle("類別管理");
        topbarFoodIngredients.addLeftBackImageButton().setOnClickListener(v -> killMyself());
    }

    @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) {
            //添加二級分類
            List<CategoryBean> data = baseCategoryAdapter.getData();
            CategoryBean categoryBean = data.get(baseCategoryAdapter.getSelectedIndex());
            parentCategoryName = categoryBean.getCategoryName();
            parentId = categoryBean.getId();
            level = mPresenter.secondCategoryTag;
        } else if (viewId == R.id.tv_new_third_category) {
            //添加三級分類
            FoodCategoryResultBean.DataBean.FoodCategoryBean selectData = secondCategoryAdapter.getSelectData();
            parentCategoryName = selectData.getName();
            parentId = selectData.getId();
            level = mPresenter.thirdCategoryTag;
        }
        String finalParentCategoryName = parentCategoryName;
        int finalParentId = parentId;
        int finalLevel = level;
        new DialogUtils(mContext, R.layout.dialog_new_category) {
            @Override
            public void initLayout(ViewHepler hepler, Dialog dialog) {
                hepler.setText(R.id.tv_parent_category_name, finalParentCategoryName);
                EditText editText = hepler.getView(R.id.ed_new_category_name);
                editText.setFilters(new InputFilter[]{InputFilterUtils.getLengthFilter(mContext, 4), InputFilterUtils.getChAndEnAndNumInputFilter(mContext)});
                hepler.setOnClickListenter(R.id.btn_create_category, v1 -> {
                    if (TextUtil.isEmptyOrNullOrUndefined(editText)) {
                        ToastUtils.show(mContext, "請輸入分類名稱");
                        return;
                    }
                    //創建分類
                    mPresenter.addCategory(finalParentId, editText.getText().toString(), finalLevel);
                    dialog.dismiss();
                });
                hepler.setOnClickListenter(R.id.iv_create_category_close, v12 -> dialog.dismiss());
            }
        }.show();
    }

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

    @Override
    public void loadCategoryInfo(List<FoodCategoryResultBean.DataBean.FoodCategoryBean> list, int hierarchy) {
        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);
                } 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) {
        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);
        }

    }

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