package xn.hxp.weidith

import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView

class FlowLayoutLayoutManager(private val itemsPerLine: Int) : RecyclerView.LayoutManager() {

    private val horizontalSpacing = 12 // 水平间距
    private val verticalSpacing = 20   // 垂直间距

    override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
        return RecyclerView.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
    }

    override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
        if (state?.itemCount == 0) {
            removeAndRecycleAllViews(recycler!!)
            return
        }

        var width = width
        var xPos = paddingLeft
        var yPos = paddingTop

        // 遍历所有可见的项目进行布局
        for (i in 0 until itemCount) {
            val child = recycler!!.getViewForPosition(i)
            addView(child)

            measureChildWithMargins(child, 0, 0)
            val childWidth = getDecoratedMeasuredWidth(child)
            val childHeight = getDecoratedMeasuredHeight(child)

            if (xPos + childWidth <= width - paddingRight) {
                layoutDecorated(child, xPos, yPos, xPos + childWidth, yPos + childHeight)
                xPos += childWidth + horizontalSpacing

                // 每行末尾换行
                if ((i + 1) % itemsPerLine == 0) {
                    xPos = paddingLeft
                    yPos += childHeight + verticalSpacing
                }
            } else {
                xPos = paddingLeft
                yPos += childHeight + verticalSpacing
                layoutDecorated(child, xPos, yPos, xPos + childWidth, yPos + childHeight)
                xPos += childWidth + horizontalSpacing
            }
        }
    }
}