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

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.R2;
import com.gingersoft.supply_chain.di.component.DaggerCategorySelectComponent;
import com.gingersoft.supply_chain.mvp.bean.OrderCategoryBean;
import com.gingersoft.supply_chain.mvp.contract.CategorySelectContract;
import com.gingersoft.supply_chain.mvp.presenter.CategorySelectPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.SelectCategoryAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.jess.arms.di.component.AppComponent;
import com.qmuiteam.qmui.widget.QMUITopBar;

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

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Description: 選擇食材類別
 *
 * @author admin
 */
public class CategorySelectFragment extends BaseSupplyChainFragment<CategorySelectPresenter> implements CategorySelectContract.View, View.OnClickListener {
    /**
     * 選擇食材類別RequestCode
     */
    public final static int SELECT_FOOD_CATEGORY_REQUEST_CODE = 1030;
    /**
     * 選擇食材類別resultCode
     */
    public final static int SELECT_FOOD_CATEGORY_RESULT_CODE = 1031;

    @BindView(R2.id.food_ingredients_category_topbar)
    QMUITopBar mTopBar;
    @BindView(R2.id.rv_food_select_category)
    RecyclerView rvCategory;

    private SelectCategoryAdapter selectCategoryAdapter;
    private int[] categoryPosition;
    /**
     * 選中的分類數據key
     */
    public final static String SELECT_CATEGORY_DATA_KEY = "categoryKey";
    private final static String CATEGORY_NAME_KEY = "categoryNameKey";
    /**
     * 默認選中的分類
     */
    private String categoryName;

    public static CategorySelectFragment newInstance(String categoryName) {
        CategorySelectFragment fragment = new CategorySelectFragment();
        Bundle bundle = new Bundle();
        bundle.putString(CATEGORY_NAME_KEY, categoryName);
        fragment.setArguments(bundle);
        return fragment;
    }

    public static CategorySelectFragment newInstance() {
        return newInstance(null);
    }

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        initTopBar(mTopBar, "選擇分類");
        Bundle arguments = getArguments();
        if (arguments != null) {
            categoryName = arguments.getString(CATEGORY_NAME_KEY);
        }
        mPresenter.getCategoryTrees();
    }


    @OnClick({R2.id.btn_food_ingredients_confirm, R2.id.btn_food_ingredients_supplier_cancel})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.btn_food_ingredients_supplier_cancel) {
            killMyself();
        } else if (viewId == R.id.btn_food_ingredients_confirm) {
            //確認
            if (selectCategoryAdapter != null) {
                Bundle bundle = new Bundle();
                List<OrderCategoryBean.FoodCategoryTrees> selectCategory = new ArrayList<>();
                List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees = selectCategoryAdapter.getData();
                getSelectCate(selectCategory, foodCategoryTrees, 0);
                bundle.putSerializable(SELECT_CATEGORY_DATA_KEY, (Serializable) selectCategory);
                setFragmentResult(SELECT_FOOD_CATEGORY_RESULT_CODE, bundle);
                killMyself();
            }
        }
    }

    /**
     * 獲取選中的分類集合
     *
     * @param selectCategory    用於裝選中的分類數據集合
     * @param foodCategoryTrees 分類樹
     * @param level             當前是第幾級分類
     */
    private void getSelectCate(List<OrderCategoryBean.FoodCategoryTrees> selectCategory, List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees, int level) {
        if (foodCategoryTrees == null) {
            return;
        }
        if (level < categoryPosition.length) {
            int position = categoryPosition[level];
            if (position != -1 && position < foodCategoryTrees.size()) {
                OrderCategoryBean.FoodCategoryTrees category = foodCategoryTrees.get(position);
                selectCategory.add(category);
                getSelectCate(selectCategory, category.getFoodCategoryTrees(), level + 1);
            }
        }
    }

    private void getCategoryIndexByName(String name, List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees) {
        if (foodCategoryTrees == null) {
            return;
        }
        for (int i = 0; i < foodCategoryTrees.size(); i++) {
            OrderCategoryBean.FoodCategoryTrees firstCategory = foodCategoryTrees.get(i);
            List<OrderCategoryBean.FoodCategoryTrees> secondCategoryTrees = firstCategory.getFoodCategoryTrees();
            if (name.equals(firstCategory.getName())) {
                //如果分類的名字一樣，說明是這個分類
                categoryPosition = new int[]{i, -1, -1};
                return;
            } else if (secondCategoryTrees != null) {
                //如果不是這個分類，遍歷這個分類下的分類
                for (int j = 0; j < secondCategoryTrees.size(); j++) {
                    OrderCategoryBean.FoodCategoryTrees secondCategory = secondCategoryTrees.get(j);
                    List<OrderCategoryBean.FoodCategoryTrees> thirdCategoryTress = secondCategory.getFoodCategoryTrees();
                    if (name.equals(secondCategory.getName())) {
                        //如果分類的名字一樣，說明是這個分類
                        categoryPosition = new int[]{i, j, -1};
                        return;
                    } else if (thirdCategoryTress != null) {
                        //如果不是這個二級分類並且第三級分類不為空，找第三級分類
                        for (int k = 0; k < thirdCategoryTress.size(); k++) {
                            OrderCategoryBean.FoodCategoryTrees thirdCategory = thirdCategoryTress.get(k);
                            if (name.equals(thirdCategory.getName())) {
                                //如果分類的名字一樣，說明是這個分類
                                categoryPosition = new int[]{i, j, k};
                                return;
                            }
                            //沒有第四級分類
                        }
                    }
                }
            }
        }
    }

    @Override
    public void loadFoodCategory
            (List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees) {
        if (TextUtil.isNotEmptyOrNullOrUndefined(categoryName)) {
            getCategoryIndexByName(categoryName, foodCategoryTrees);
        }
        if (categoryPosition == null) {
            categoryPosition = new int[]{0, -1, -1};
        }
        selectCategoryAdapter = new SelectCategoryAdapter(foodCategoryTrees, Color.WHITE, 0, categoryPosition);
        rvCategory.setAdapter(selectCategoryAdapter);
        selectCategoryAdapter.setOnChildSelectListener((position, isChecked) -> {
            selectCategoryAdapter.notifyDataSetChanged();
        });
    }
}
