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 androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.ui.adapter.BaseRadioSectionAdapter;
import com.gingersoft.gsa.cloud.ui.bean.SectionCheckItem;
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.contract.CategorySelectContract;
import com.gingersoft.supply_chain.mvp.presenter.CategorySelectPresenter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.jess.arms.di.component.AppComponent;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.section.QMUISection;
import com.qmuiteam.qmui.widget.section.QMUIStickySectionAdapter;
import com.qmuiteam.qmui.widget.section.QMUIStickySectionLayout;

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

import butterknife.BindView;
import butterknife.OnClick;
import static com.gingersoft.gsa.cloud.ui.adapter.BaseRadioSectionAdapter.SEPARATOR;


/**
 * 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.food_ingredients_category_section_layout)
    QMUIStickySectionLayout sectionLayout;
    /**
     * 選中的分類數據key
     */
    public final static String SELECT_CATEGORY_DATA_KEY = "categoryKey";

    public static CategorySelectFragment newInstance() {
        CategorySelectFragment fragment = new CategorySelectFragment();
        return fragment;
    }

    @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, "選擇分類");
        mPresenter.getFoodCategoryList(null, 0, "0");
    }


    @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 (baseRadioSectionAdapter != null) {
                Bundle bundle = new Bundle();
                List<QMUISection<SectionCheckItem, SectionCheckItem>> currentData = baseRadioSectionAdapter.getCurrentData();
                List<SectionCheckItem> putSectionCheckItems = new ArrayList<>();
                for (int i = 0; i < currentData.size(); i++) {
                    if (currentData.get(i).getHeader().isChecked()) {
                        putSectionCheckItems.add(currentData.get(i).getHeader());
                        if (currentData.get(i).getItemList() != null) {
                            getCheckInfo(currentData.get(i).getItemList(), putSectionCheckItems);
                        }
                        break;
                    }
                }
                bundle.putSerializable(SELECT_CATEGORY_DATA_KEY, (Serializable) putSectionCheckItems);
                setFragmentResult(SELECT_FOOD_CATEGORY_RESULT_CODE, bundle);
                killMyself();
            }
        }
    }

    private void getCheckInfo(List<SectionCheckItem> sectionCheckItems, List<SectionCheckItem> putSectionCheckItems) {
        for (SectionCheckItem sectionCheckItem : sectionCheckItems) {
            if (sectionCheckItem.isChecked()) {
                putSectionCheckItems.add(sectionCheckItem);
                if (sectionCheckItem.getSectionCheckItems() != null) {
                    getCheckInfo(sectionCheckItem.getSectionCheckItems(), putSectionCheckItems);
                }
                break;
            }
        }
    }

    private BaseRadioSectionAdapter baseRadioSectionAdapter;
    private String lastCheckPositions = "0";

    @Override
    public void loadFoodCategory(List<QMUISection<SectionCheckItem, SectionCheckItem>> sections) {
        if (baseRadioSectionAdapter == null) {
            baseRadioSectionAdapter = new BaseRadioSectionAdapter(mContext);
            sections.get(0).getHeader().setChecked(true);
            baseRadioSectionAdapter.setData(sections);
            sectionLayout.setLayoutManager(new LinearLayoutManager(getContext()) {
                @Override
                public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                    return new RecyclerView.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                }
            });
            sectionLayout.setAdapter(baseRadioSectionAdapter);
        } else {
            setCheckState(sections, lastCheckPositions, true);
            baseRadioSectionAdapter.setData(sections);
        }
        //設置默認選中
        baseRadioSectionAdapter.setOnCheckedChangeListener((positions, isChecked, section) -> {
            //獲得上一次選中的數據
            if (section != null) {
                positions = section.getSort() + "";
            }
            if (TextUtil.isNotEmptyOrNullOrUndefined(positions)) {
                //將上次的設為未選中
                setCheckState(sections, lastCheckPositions, false);

                setCheckState(sections, positions, isChecked);
                refreshAdapter();
                lastCheckPositions = positions;
            } else if (TextUtil.isNotEmptyOrNullOrUndefined(lastCheckPositions) && isChecked) {
                //將上次選中的設置為未選中
                setCheckState(sections, lastCheckPositions, false);
            }
        });
        baseRadioSectionAdapter.setOnRefreshListener(this::refreshAdapter);
        baseRadioSectionAdapter.setCallback(new QMUIStickySectionAdapter.Callback<SectionCheckItem, SectionCheckItem>() {
            @Override
            public void loadMore(QMUISection<SectionCheckItem, SectionCheckItem> section, boolean loadMoreBefore) {

            }

            @Override
            public void onItemClick(QMUIStickySectionAdapter.ViewHolder holder, int position) {
                if (position < sections.size() && sections.get(position).getItemCount() <= 0) {
                    if (holder instanceof BaseRadioSectionAdapter.HeaderViewHolder) {
                        BaseRadioSectionAdapter.HeaderViewHolder viewHolder = (BaseRadioSectionAdapter.HeaderViewHolder) holder;
                        int index = viewHolder.getSectionCheckItemItem(position);
                        mPresenter.getFoodCategoryList(null, sections.get(index).getHeader().getId(), index + "");
                    }
                } else {
                    baseRadioSectionAdapter.toggleFold(position, false);
                }
            }

            @Override
            public boolean onItemLongClick(QMUIStickySectionAdapter.ViewHolder holder, int position) {
                return false;
            }
        });
        baseRadioSectionAdapter.setOnItemClickListener((id, position1, positions) -> mPresenter.getFoodCategoryList(null, id, position1 + SEPARATOR + positions));
    }

    private void setCheckState(List<QMUISection<SectionCheckItem, SectionCheckItem>> sections, String lastCheckPositions, boolean b) {
        String[] lastSplit = lastCheckPositions.split(SEPARATOR);
        if (Integer.parseInt(lastSplit[0]) != -1) {
            sections.get(Integer.parseInt(lastSplit[0])).getHeader().setChecked(b);
            getTheDeepest(sections.get(Integer.parseInt(lastSplit[0])).getItemList(), lastSplit, 1, b);
        }
    }

    private void refreshAdapter() {
        if (sectionLayout.getRecyclerView().isComputingLayout()) {
            sectionLayout.getRecyclerView().post(() -> baseRadioSectionAdapter.notifyDataSetChanged());
        } else {
            baseRadioSectionAdapter.notifyDataSetChanged();
        }
    }

    public void getTheDeepest(List<SectionCheckItem> sections, String[] split, int i, boolean isChecked) {
        if (sections != null && i < split.length) {
            if (sections.size() > 0) {
                sections.get(Integer.parseInt(split[i])).setChecked(isChecked);
                getTheDeepest(sections.get(Integer.parseInt(split[i])).getSectionCheckItems(), split, i + 1, isChecked);
            }
        } else if (sections != null) {
            for (int j = 0; j < sections.size(); j++) {

            }
        }
    }
}
