package com.hainaos.vc.view;

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

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

public class EquallyDividedItemDecoration extends RecyclerView.ItemDecoration {
    private static final String TAG = "EquallyDividedItemDecoration";

    private int mSpanCount;// 横条目数量
    private int mHalfRowSpacing;// 行间距的一半
    private int mHalfColumnSpacing;// 列间距的一半

    public EquallyDividedItemDecoration(int spanCount, int halfRowSpacing) {
        mSpanCount = spanCount;
        mHalfRowSpacing = halfRowSpacing;
        mHalfColumnSpacing = halfRowSpacing;
    }

    public EquallyDividedItemDecoration(int spanCount, int halfRowSpacing, int halfColumnSpacing) {
        mSpanCount = spanCount;
        mHalfRowSpacing = halfRowSpacing;
        mHalfColumnSpacing = halfColumnSpacing;
    }

    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent,
            @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int position = parent.getChildAdapterPosition(view); // 获取view 在adapter中的位置。
        Log.d(TAG, "getItemOffsets: position = " + position);

        int itemCount = parent.getAdapter().getItemCount();// item全部数量
        Log.d(TAG, "getItemOffsets: itemCount = " + itemCount);

        int column = position % mSpanCount; // view 所在的列
        Log.d(TAG, "getItemOffsets: column = " + column);

        if (column == 0) {
            outRect.left = 2 * mHalfRowSpacing;
            outRect.right = mHalfRowSpacing;
        } else if (column == mSpanCount - 1) {
            outRect.left = mHalfRowSpacing;
            outRect.right = 2 * mHalfRowSpacing;
        } else {
            outRect.left = mHalfRowSpacing;
            outRect.right = mHalfRowSpacing;
        }

        int row = (position / mSpanCount);// 所在行
        Log.d(TAG, "getItemOffsets: row = " + row);
        int maxRow = (int) Math.ceil((double) itemCount / mSpanCount);// 一共多少行
        Log.d(TAG, "getItemOffsets: maxRow = " + maxRow);

        if (row == 0) {
            outRect.top = 2 * mHalfColumnSpacing;
            outRect.bottom = mHalfColumnSpacing;
        } else if (row == maxRow - 1) {
            outRect.top = mHalfColumnSpacing;
            outRect.bottom = 2 * mHalfColumnSpacing;
        } else {
            outRect.top = mHalfColumnSpacing;
            outRect.bottom = mHalfColumnSpacing;
        }

        Log.d(TAG, "getItemOffsets: outRect.left = " + outRect.left);
        Log.d(TAG, "getItemOffsets: outRect.right = " + outRect.right);
        Log.d(TAG, "getItemOffsets: outRect.top = " + outRect.top);
        Log.d(TAG, "getItemOffsets: outRect.bottom = " + outRect.bottom);
    }
}
