package com.remax.visualnovel.widget.itemdecoration

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView

/**
 * Created by HJW on 2020/11/19
 * @params 横条目数量,行间距,列间距
 */
class GridSpaceItemDecoration(
    private val spanCount: Int,
    private val rowSpacing: Int = 0,//行间距
    private val columnSpacing: Int = 0, //列间距
    private val hasHead: Boolean = false
) :
    RecyclerView.ItemDecoration() {

    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
        val position = parent.getChildAdapterPosition(view) // 获取view 在adapter中的位置。

        if (hasHead) {
            if (position != 0) {
                var column = position % spanCount - 1 // view 所在的列
                if (column == -1) column = spanCount - 1
                outRect.left = column * columnSpacing / spanCount // column * (列间距 * (1f / 列数))

                outRect.right = columnSpacing - (column + 1) * columnSpacing / spanCount // 列间距 - (column + 1) * (列间距 * (1f /列数))

            }
            outRect.bottom = rowSpacing // item top
        } else {
            val column = position % spanCount // view 所在的列

            outRect.left = column * columnSpacing / spanCount // column * (列间距 * (1f / 列数))
            outRect.right = columnSpacing - (column + 1) * columnSpacing / spanCount // 列间距 - (column + 1) * (列间距 * (1f /列数))

            outRect.bottom = rowSpacing // item top
        }

    }
}