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

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gingersoft.gsa.cloud.common.loadsir.EmptyCallback;
import com.gingersoft.gsa.cloud.common.loadsir.ErrorCallback;
import com.gingersoft.gsa.cloud.ui.bean.view.CategoryBean;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.R2;
import com.gingersoft.supply_chain.di.component.DaggerBuyIngredientsComponent;
import com.gingersoft.supply_chain.mvp.bean.OrderCategoryBean;
import com.gingersoft.supply_chain.mvp.bean.PurchaseFoodBean;
import com.gingersoft.supply_chain.mvp.contract.BuyIngredientsContract;
import com.gingersoft.supply_chain.mvp.presenter.BuyIngredientsPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.BuyIngredientsAdapter;
import com.gingersoft.supply_chain.mvp.ui.adapter.FirstLevelCategoryAdapter;
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.ShowSecondCategoryPopup;
import com.gingersoft.supply_chain.mvp.utils.ViewUtils;
import com.jess.arms.di.component.AppComponent;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.enums.PopupPosition;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.alpha.QMUIAlphaImageButton;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.section.QMUISection;
import com.qmuiteam.qmui.widget.section.QMUIStickySectionLayout;

import org.jetbrains.annotations.NotNull;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import lombok.val;


/**
 * Description: 選購食材
 */
public class BuyIngredientsFragment extends BaseSupplyChainFragment<BuyIngredientsPresenter> implements BuyIngredientsContract.View, View.OnClickListener {

    @BindView(R2.id.topbar_food_ingredients)
    QMUITopBar topbarFoodIngredients;
    @BindView(R2.id.layout_purchase_food_content)
    RelativeLayout layoutContent;
    @BindView(R2.id.ed_food_ingredients_search)
    EditText edFoodIngredientsSearch;
    @BindView(R2.id.layout_food_ingredients_search)
    LinearLayout layoutFoodIngredientsSearch;
    @BindView(R2.id.tv_switch_food_ingredients_show_type)
    QMUIAlphaTextView tvSwitchFoodIngredientsShowType;
    @BindView(R2.id.rv_food_ingredients_category)
    RecyclerView rvFirstCategory;
    private FirstLevelCategoryAdapter firstLevelCategoryAdapter;

    @BindView(R2.id.layout_right_content)
    LinearLayout layoutRightContent;
    @BindView(R2.id.layout_ingredients_left)
    LinearLayout layoutIngredientsLeft;
    @BindView(R2.id.rv_food_ingredients_second_category)
    RecyclerView rvSecondCategory;
    private SecondCategoryAdapter secondCategoryAdapter;

    @BindView(R2.id.section_food_ingredients)
    QMUIStickySectionLayout sectionFood;
    private BuyIngredientsAdapter adapter;
    //    @BindView(R2.id.rv_food_ingredients)
//    RecyclerView rvFoodIngredients;
    @BindView(R2.id.srl_supplier)
    LinearLayout srlSupplier;
    @BindView(R2.id.btn_new_food_ingredient)
    QMUIAlphaButton btnNewFoodIngredient;
    @BindView(R2.id.btn_food_ingredients_confirm)
    QMUIAlphaButton btnFoodIngredientsConfirm;
    @BindView(R2.id.tv_ingredients_food_num)
    TextView tvIngredientsFoodNum;
    @BindView(R2.id.btn_food_ingredients_cancel)
    QMUIAlphaButton btnFoodIngredientsCancel;
    @BindView(R2.id.layout_food_ingredients_btn)
    LinearLayout layoutFoodIngredientsBtn;
    @BindView(R2.id.btn_switch_row)
    QMUIAlphaImageButton btnSwitchRow;
    @BindView(R2.id.layout_category)
    LinearLayout layoutCategory;
    @BindView(R2.id.card_show_more_category)
    CardView cardMoreCategory;
    @BindView(R2.id.iv_unfold_arrow)
    ImageView ivUnfoldArrow;
    @BindView(R2.id.tv_unfold_category)
    TextView tvUnfoldCategory;
    TextView tvShoppingCart;
    /**
     * 0單列
     * 1雙列
     */
    private boolean isSinger = true;

    private LoadService fullRegister;

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

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        initTopBar();
        loadService = LoadSir.getDefault().register(layoutRightContent, (Callback.OnReloadListener) v -> {
        });
        fullRegister = LoadSir.getDefault().register(layoutContent, (Callback.OnReloadListener) v -> {
        });
        //獲取一級分類
        mPresenter.getCategoryTrees();
    }

    private void initTopBar() {
        initTopBar(topbarFoodIngredients, "食材管理");
        View view = View.inflate(requireContext(), R.layout.view_shopping_car, null);
        tvShoppingCart = view.findViewById(R.id.tv_purchase_cart_number);
        topbarFoodIngredients.addRightView(view, R.id.qmui_shopping_cart);
    }

    @OnClick({R2.id.layout_food_ingredients_search, R2.id.tv_switch_food_ingredients_show_type, R2.id.btn_food_ingredients_confirm,
            R2.id.btn_food_ingredients_cancel, R2.id.btn_switch_row, R2.id.card_show_more_category})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.layout_food_ingredients_search) {
            //跳轉搜索頁面
            jumpToSearch();
        } else if (viewId == R.id.btn_switch_row) {
            //切換顯示單雙列
            switchShowSingerOrDouble();
        } else if (viewId == R.id.tv_switch_food_ingredients_show_type) {
            //切換顯示分類或是顯示供應商
            switchShowCategoryOrSupplier();
        } else if (viewId == R.id.card_show_more_category) {
            //展開分類
            unfoldCategory();
        } else if (viewId == R.id.btn_food_ingredients_confirm) {
            //確認
            confirm();
        } else if (viewId == R.id.btn_food_ingredients_cancel) {
            //取消
            killMyself();
        }
    }

    /**
     * 跳轉到搜索頁面
     */
    private void jumpToSearch() {

    }

    /**
     * 切換顯示單列或雙列
     */
    private void switchShowSingerOrDouble() {
        //切換單雙列
        isSinger = !isSinger;
        sectionFood.setLayoutManager(isSinger ? new LinearLayoutManager(requireContext()) : getDoubleRowManager());
        adapter.setShowDoubleRow(isSinger);
        btnSwitchRow.setImageResource(isSinger ? R.drawable.ic_single_row : R.drawable.ic_double_row);
        sectionFood.setAdapter(adapter);
    }

    /**
     * 切換顯示分類或供應商
     */
    private void switchShowCategoryOrSupplier() {

    }

    /**
     * 展開二級分類
     */
    private void unfoldCategory() {
        if (secondCategoryAdapter == null) {
            return;
        }
        new XPopup.Builder(requireContext())
                .atView(layoutCategory)
                .hasShadowBg(false)
                .popupPosition(PopupPosition.Bottom)
                .asCustom(new ShowSecondCategoryPopup(requireContext(), secondCategoryAdapter.getSelectIndex(), layoutCategory.getWidth(), secondCategoryAdapter.getData(), (adapter, view, position) -> {
                    //二級分類滾動顯示，當前彈窗顯示三級分類，顯示三級分類在popup內部處理
                    secondCategoryAdapter.getOnItemClickListener().onItemClick(secondCategoryAdapter, view, position);
                }))
                .show();
    }

    /**
     * 確認，進入購物車頁面
     */
    private void confirm() {

    }

    @Override
    public void loadCategory(List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees) {
        if (foodCategoryTrees.size() > 0) {
            fullRegister.showSuccess();
            loadService.showSuccess();
            if (firstLevelCategoryAdapter == null) {
                firstLevelCategoryAdapter = new FirstLevelCategoryAdapter(foodCategoryTrees, requireContext());
                rvFirstCategory.setAdapter(firstLevelCategoryAdapter);
                firstLevelCategoryAdapter.setOnItemClickListener((adapter, view, position) -> {
                    //切換右側顯示的二級分類和食材
                    firstLevelCategoryAdapter.setSelectedIndex(position);
                    ViewUtils.moveToCenterByVertical(rvFirstCategory, position);
                    loadSecondCategory(firstLevelCategoryAdapter.getData().get(position).getFoodCategoryTrees());
                    //獲取當前分類所有食材
                    mPresenter.getFoodByCategoryId(firstLevelCategoryAdapter.getItem(position).getId());
                });
                //默認選中第0個分類
                firstLevelCategoryAdapter.getOnItemClickListener().onItemClick(firstLevelCategoryAdapter, null, 0);
            } else {
                firstLevelCategoryAdapter.setList(foodCategoryTrees);
            }
        } else {
            fullRegister.showCallback(ErrorCallback.class);
        }
    }

    @Override
    public void loadRightFoodIngredients(List<PurchaseFoodBean> purchaseFoodListVOS) {
        // 點擊一二三級分類，都是清空當前頁面所有食材，然後顯示當前級別分類下的食材
        // 滑動則是判斷底部，一直累加數據
        sectionFood.setLayoutManager(new LinearLayoutManager(requireContext()));
    }

    @Override
    public void loadFail() {
        loadService.showCallback(EmptyCallback.class);
    }

    /**
     * 加載二級分類
     *
     * @param foodCategoryTrees
     */
    private void loadSecondCategory(List<OrderCategoryBean.FoodCategoryTrees> foodCategoryTrees) {
        secondCategoryAdapter = new SecondCategoryAdapter(requireContext(), foodCategoryTrees);
        rvSecondCategory.setLayoutManager(new LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false));
        rvSecondCategory.setAdapter(secondCategoryAdapter);
        OnItemClickListener onItemClickListener = (adapter, view, position) -> {
            secondCategoryAdapter.setSelectIndex(position);
            ViewUtils.moveToCenterByHorizontal(rvSecondCategory, position);
            //加載當前分類下的食品

        };
        secondCategoryAdapter.setOnItemClickListener(onItemClickListener);
        //默認選中第0個
        if (foodCategoryTrees != null && foodCategoryTrees.size() > 0) {
            onItemClickListener.onItemClick(secondCategoryAdapter, rvSecondCategory, 0);
        }
    }

    @Override
    public void loadFood(List<QMUISection<CategoryBean, PurchaseFoodBean>> food) {
        if (adapter == null) {
            adapter = new BuyIngredientsAdapter(requireContext(), food);
            sectionFood.setAdapter(adapter);
        } else {
            adapter.setData(food);
        }
        if (isSinger) {
            sectionFood.setLayoutManager(new LinearLayoutManager(requireContext()));
        } else {
            sectionFood.setLayoutManager(getDoubleRowManager());
        }
    }

    @NotNull
    private GridLayoutManager getDoubleRowManager() {
        val gridLayoutManager = new GridLayoutManager(requireContext(), 2);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return adapter.getItemIndex(position) < 0 ? gridLayoutManager.getSpanCount() : 1;
            }
        });
        return gridLayoutManager;
    }
}
