package com.gh.gamecenter.common.view

import android.content.Context
import android.view.ViewGroup.MarginLayoutParams
import androidx.recyclerview.widget.RecyclerView

/**
 * 重写computeVerticalScrollOffset,精确计算RecyclerView滑动距离
 */
class OffsetLinearLayoutManager(context: Context?) : ScrollableLinearLayoutManager(context) {
    val heightMap = linkedMapOf<Int, Int>()
    override fun onLayoutCompleted(state: RecyclerView.State) {
        super.onLayoutCompleted(state)
        val count = childCount
        for (i in 0 until count) {
            val view = getChildAt(i)
            if (view?.layoutParams is MarginLayoutParams) {
                heightMap[i] = view.height + (view.layoutParams as MarginLayoutParams).topMargin + (view.layoutParams as MarginLayoutParams).bottomMargin
            } else {
                heightMap[i] = view?.height ?: 0
            }
        }
    }

    override fun computeVerticalScrollOffset(state: RecyclerView.State): Int {
        return if (childCount != 0) {
            try {
                val firstVisiblePosition = findFirstVisibleItemPosition()
                val firstVisibleView = findViewByPosition(firstVisiblePosition)
                var offsetY = -(firstVisibleView?.y ?: 0).toInt() + ((firstVisibleView?.layoutParams as? MarginLayoutParams)?.topMargin ?: 0)
                for (i in 0 until firstVisiblePosition) {
                    offsetY += (if (heightMap[i] == null) 0 else heightMap[i] ?: 0)
                }
                offsetY
            } catch (e: Exception) {
                0
            }
        } else 0
    }
}