package com.abbidot.tracker.adapter

import android.content.Context
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.qmuiteam.qmui.util.QMUIDisplayHelper

/**
 *Created  by .
 * @link https://blog.csdn.net/Lee465357793/article/details/130830127
 * @description:RecyclerView GridLayoutManager item间距设置，两端对齐
 * @param offset 控件的外边距，不使用屏幕宽度来计算
 */
class GridItemDecoration(
    context: Context, spanCount: Int, private var itemWidth: Int, top: Int, bottom: Int, offset: Int
) : RecyclerView.ItemDecoration() {

    private var mSpanCount = spanCount
    private val mContext = context
    private var mColumnSpacing = 0
    private val mTop = top
    private val mBottom = bottom

    private val rvWidth by lazy {
        QMUIDisplayHelper.getScreenWidth(mContext) - offset
    }

    init {
        mColumnSpacing = (rvWidth - (itemWidth * mSpanCount)) / (mSpanCount - 1)
    }

    fun updateSpaceCount(count: Int) {
        mSpanCount = count
        mColumnSpacing = (rvWidth - (itemWidth * mSpanCount)) / (mSpanCount - 1)
    }

    override fun getItemOffsets(
        outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State
    ) {
        // 获取view 在adapter中的位置。
        val position = parent.getChildAdapterPosition(view)
        // view 所在的列
        val column = position % mSpanCount
        // column * (列间距 * (1f / 列数))
        outRect.left = (column * mColumnSpacing / mSpanCount)
        // 列间距 - (column + 1) * (列间距 * (1f /列数))
        outRect.right = (mColumnSpacing - (column + 1) * mColumnSpacing / mSpanCount)

        if (mTop > 0) {
            outRect.top = mTop
        }
        if (mBottom > 0) {
            outRect.bottom = mBottom
        }
    }
}