package com.gingersoft.supply_chain.mvp.ui.adapter.dishes;

import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;

import androidx.core.view.ViewCompat;

import com.chad.library.adapter.base.entity.node.BaseNode;
import com.chad.library.adapter.base.provider.BaseNodeProvider;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.gingersoft.supply_chain.R;

import org.jetbrains.annotations.NotNull;

import java.util.List;

public class DishesGroupProvider extends BaseNodeProvider {
    @Override
    public int getItemViewType() {
        return DishesTreeAdapter.DISHESGROUP;
    }

    @Override
    public int getLayoutId() {
        return R.layout.item_dish_group;
    }

    @Override
    public void convert(@NotNull BaseViewHolder baseViewHolder, BaseNode baseNode) {
        DishesGroupNode entity = (DishesGroupNode) baseNode;
        baseViewHolder.setText(R.id.tv_dishes_group_title, entity.getTitle());
        baseViewHolder.setImageResource(R.id.iv_dishes_group_icon, R.mipmap.ic_launcher);

        setArrowSpin(baseViewHolder, baseNode, false);

    }


    @Override
    public void convert(@NotNull BaseViewHolder helper, @NotNull BaseNode data, @NotNull List<?> payloads) {
        for (Object payload : payloads) {
            if (payload instanceof Integer && (int) payload == DishesTreeAdapter.EXPAND_COLLAPSE_PAYLOAD) {
                // 增量刷新，使用动画变化箭头
                setArrowSpin(helper, data, true);
            }
        }
    }

    private void setArrowSpin(BaseViewHolder helper, BaseNode data, boolean isAnimate) {
        DishesGroupNode entity = (DishesGroupNode) data;

        ImageView imageView = helper.getView(R.id.iv_dishes_group_icon);

        if (entity.isExpanded()) {
            if (isAnimate) {
                ViewCompat.animate(imageView).setDuration(200)
                        .setInterpolator(new DecelerateInterpolator())
                        .rotation(0f)
                        .start();
            } else {
                imageView.setRotation(0f);
            }
        } else {
            if (isAnimate) {
                ViewCompat.animate(imageView).setDuration(200)
                        .setInterpolator(new DecelerateInterpolator())
                        .rotation(90f)
                        .start();
            } else {
                imageView.setRotation(90f);
            }
        }
    }

    @Override
    public void onClick(@NotNull BaseViewHolder helper, @NotNull View view, BaseNode data, int position) {
        // 这里使用payload进行增量刷新（避免整个item刷新导致的闪烁，不自然）
        getAdapter().expandOrCollapse(position, true, true, DishesTreeAdapter.EXPAND_COLLAPSE_PAYLOAD);
    }
}
