package com.example.base.decoration

import android.R.attr.divider
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import androidx.recyclerview.widget.StaggeredGridLayoutManager


/**
 * 描述 : RecyclerView GridLayoutManager 等间距。
 *
 *
 * 等间距需满足两个条件：
 * 1.各个模块的大小相等，即 各列的left+right 值相等；
 * 2.各列的间距相等，即 前列的right + 后列的left = 列间距；
 *
 *
 * 在[.getItemOffsets] 中针对 outRect 的left 和right 满足这两个条件即可
 *
 *
 * 作者 : shiguotao
 * 版本 : V1
 * 创建时间 : 2020/3/19 4:54 PM
 */

/**
 * @param mSpanCount     列数
 * @param mRowSpacing    行间距
 * @param mColumnSpacing 列间距
 */
class StaggeredSpaceItemDecoration(
    private val mSpanCount: Int,//横条目数量
    private val mRowSpacing: Int,  //行间距
    private val mColumnSpacing: Int// 列间距
) :
    ItemDecoration() {
    private val TAG = "StaggeredSpaceItemDecoration"

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        val layoutParams = view.layoutParams as StaggeredGridLayoutManager.LayoutParams
        val spanIndex = layoutParams.getSpanIndex()
        if (spanIndex == 0) {
            // left
            outRect.left = mRowSpacing
            outRect.right = mRowSpacing / 2

            outRect.top = mColumnSpacing
            outRect.bottom = mColumnSpacing / 2
        } else {
            outRect.right = mRowSpacing
            outRect.left = mRowSpacing / 2

            outRect.bottom = mColumnSpacing
            outRect.top = mColumnSpacing / 2
        }
    }

}
