package com.gingersoft.supply_chain.mvp.utils;

import android.util.Log;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * @author 宇航.
 * User: admin
 * Date: 2021/3/11
 * Time: 14:59
 * Use:
 */
public class ViewUtils {


    public static void moveToCenterByVertical(RecyclerView recyclerView, int sectionPosition) {
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        if (layoutManager == null) {
            return;
        }
        //取得中間位置的item
        View childAt = recyclerView.getChildAt(sectionPosition - layoutManager.findFirstVisibleItemPosition());
        //拿到列表一半的高度
        int halfLeftRvHeight = recyclerView.getHeight() / 2;
        if (childAt != null) {
            //中間位置那個item減去一半的高度等於中間item一半顯示在列表中間
            int y = childAt.getTop() - halfLeftRvHeight;
            recyclerView.smoothScrollBy(0, y);
        }
    }

    public static void moveToCenterByHorizontal(RecyclerView recyclerView, int sectionPosition) {
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        if (layoutManager == null) {
            return;
        }
        //取得中間位置的item
        Log.e("eee", "需要選中：" + sectionPosition + "顯示的：" + layoutManager.findFirstVisibleItemPosition() + "子數量：" + recyclerView.getChildCount());
//        View childAt = recyclerView.getChildAt(sectionPosition - layoutManager.findFirstVisibleItemPosition());
        View childAt = layoutManager.findViewByPosition(sectionPosition - layoutManager.findFirstVisibleItemPosition());
        //拿到列表一半的寬度
        int halfLeftRvWidth = recyclerView.getWidth() / 2;
        Log.e("eee", childAt + "一半寬度：" + halfLeftRvWidth + "第一個：" + recyclerView.getChildAt(0));
        if (childAt != null) {
            //中間位置那個item減去一半的高度等於中間item一半顯示在列表中間
            int x = childAt.getLeft() - halfLeftRvWidth;
            recyclerView.smoothScrollBy(x, 0);
        } else {
            layoutManager.scrollToPositionWithOffset(sectionPosition, 0);
        }
    }
}
