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.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.listener.OnItemClickListener;
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.Constant;
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.lxj.xpopup.XPopup;
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.tv_new_second_category)
    QMUIAlphaTextView addSecondCategory;
    @BindView(R2.id.layout_category)
    LinearLayout layoutCategory;
    /**
     * 當前選中的是幾級分類
     */
    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.getCategoryTrees());
        initTopBar();
        mPresenter.getCategoryTrees();
    }

    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() {
        OrderCategoryBean.FoodCategoryTrees foodCategoryTrees;
        int position;
        if (currentLevel == mPresenter.primaryCategoryTag) {
            foodCategoryTrees = getCategoryInfo(categoryAdapter);
            position = categoryAdapter.getSelectIndex();
        } else if (currentLevel == mPresenter.secondCategoryTag) {
            foodCategoryTrees = getCategoryInfo(secondCategoryAdapter);
            position = secondCategoryAdapter.getSelectIndex();
        } else if (currentLevel == mPresenter.thirdCategoryTag) {
            foodCategoryTrees = getCategoryInfo(thirdCategoryAdapter);
            position = thirdCategoryAdapter.getSelectIndex();
        } else {
            showMessage("請重新選擇分類");
            return;
        }
        if (foodCategoryTrees == null) {
            showMessage("請重新選擇分類");
            return;
        }
        showEditCategoryPop(foodCategoryTrees, position);
    }

    /**
     * 顯示編輯分類彈窗
     *
     * @param foodCategoryTrees 分類信息
     * @param position          編輯的分類下標，編輯之後用於刷新
     */
    private void showEditCategoryPop(OrderCategoryBean.FoodCategoryTrees foodCategoryTrees, int position) {
        NewAddCategoryPopup categoryPopup = new NewAddCategoryPopup(mContext, "修改", "類別名稱", "请修改當前類別名稱", foodCategoryTrees.getName(), true);
        categoryPopup.setOnDeleteListener(v -> {
            //刪除分類
            AppDialog.getInstance().showWaringDialog(mContext, String.format(getString(R.string.str_delete_category_tip), foodCategoryTrees.getName()), (view, dialog) -> {
                categoryPopup.dismiss();
                mPresenter.deleteFoodCategory(foodCategoryTrees, currentLevel, position);
            });
        });
        new XPopup.Builder(getContext())
                .asCustom(categoryPopup.setListener(() -> {
                    //修改分類
                    if (TextUtil.isEmptyOrNullOrUndefined(categoryPopup.getEditText())) {
                        showMessage("請輸入分類名稱");
                        return;
                    }
                    mPresenter.updateFoodCategory(mPresenter.toFoodCategoryBean(foodCategoryTrees.getParentId(), categoryPopup.getEditText().getText().toString(), foodCategoryTrees.getId()), currentLevel, position);
                }, () -> {
                }))
                .show();
    }

    /**
     * 獲取當前分類信息
     *
     * @param categoryAdapter 分類adapter
     * @return 分類信息
     */
    private OrderCategoryBean.FoodCategoryTrees getCategoryInfo(FoodCategoryAdapter categoryAdapter) {
        if (categoryAdapter == null || categoryAdapter.getSelectIndex() == -1) {
            showMessage("请选择分类");
            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})
    @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) {
            //添加二級分類
            //拿到選中的一級分類信息
            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, "類別名稱", "请輸入類別名稱", null, false);
            new XPopup.Builder(getContext())
                    .asCustom(categoryPopup.setListener(() -> {
                        //創建分類
                        if (TextUtil.isEmptyOrNullOrUndefined(categoryPopup.getEditText())) {
                            showMessage("請輸入分類名稱");
                            return;
                        }
                        //創建分類
                        mPresenter.addCategory(parentId, categoryPopup.getEditText().getText().toString(), level);
                    }, () -> {
                    }))
                    .show();
        } else {
            showMessage("請選擇分類");
        }
    }

    //一級
    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 (categoryAdapter == null) {
            categoryAdapter = new FoodCategoryAdapter(R.layout.item_first_category, data)
                    .setUnCheckedBg(ContextCompat.getDrawable(mContext, R.color.trans))
                    .setCheckedBg(ContextCompat.getDrawable(mContext, 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);
        }
        if (categoryAdapter.getItemCount() > 0) {
            //如果有一級分類，默認顯示第一個一級分類下的二級分類
            categoryAdapter.setSelectIndex(0);
            loadSecondCategory(categoryAdapter.getItem(0).getFoodCategoryTrees());
            //顯示新增二級分類
            addSecondCategory.setVisibility(View.VISIBLE);
        } else {
            addSecondCategory.setVisibility(View.GONE);
            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(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);
                        secondCategoryAdapter.setSelectIndex(position);
                        //加載三級分類
                        loadThirdCategory(secondCategoryAdapter.getItem(position).getFoodCategoryTrees());
                    });
            rvSecondCategory.setLayoutManager(new GridLayoutManager(mContext, 3) {
                @Override
                public boolean canScrollHorizontally() {
                    return true;
                }
            });
            rvSecondCategory.setAdapter(secondCategoryAdapter);
        } else {
            //重置選中
            secondCategoryAdapter.setSelectIndex(-1);
            secondCategoryAdapter.setNewInstance(data);
        }
    }

    /**
     * 加載三級分類
     *
     * @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(-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);
                        thirdCategoryAdapter.setSelectIndex(position);
                    });
            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);
        } else if (hierarchy == mPresenter.secondCategoryTag) {
            //如果是添加的二級分類，就要拿到當前的一級分類，給一級分類的子分類集合中添加分類
            newCategory(categoryTrees, categoryAdapter);
        } 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 == Constant.DELETE) {
                //如果是刪除，就移除掉
                categoryAdapter.removeAt(position);
                if (categoryAdapter.getItemCount() > 0) {
                    // 總數量大於0，選中第0個
                    rvFirstCategory.scrollToPosition(0);
                    categoryAdapter.getOnItemClickListener().onItemClick(categoryAdapter, null, 0);
                } else {
                    //沒有一級分類了
                    //清除二級三級分類
                    secondCategoryAdapter.setList(null);
                    secondCategoryAdapter.setList(null);
                    addSecondCategory.setVisibility(View.GONE);
                    addThirdCategory.setVisibility(View.GONE);
                }
            } else if (type == Constant.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 == Constant.DELETE) {
            adapter.removeAt(position);
            if (hierarchy == mPresenter.secondCategoryTag) {
                thirdCategoryAdapter.setNewInstance(null);
                //如果是二級分類，還需要判斷如果分類數量為0時，就不顯示三級分類
                if (secondCategoryAdapter.getItemCount() <= 1) {
                    thirdCategoryAdapter.setNewInstance(null);
                    addThirdCategory.setVisibility(View.GONE);
                    //切換選中一級
                    setCurrentInfo(mPresenter.primaryCategoryTag);
                } else {
                    adapter.getOnItemClickListener().onItemClick(adapter, null, 1);
                }
            } else {
                //刪除的是三級，切換選中到二級
                setCurrentInfo(mPresenter.secondCategoryTag);
            }
        } else if (type == Constant.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);
        }
    }
}
