package com.example.base.decoration

import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Rect
import android.graphics.drawable.ColorDrawable
import android.view.View
import androidx.annotation.ColorInt
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration


/**
 * recyclerView 分割线
 */
class DividerItemDecoration(
    private val leftMargin: Int = 0,
    private val rightMargin: Int = 0,
    private val dividerHeight: Int = 2,
    @ColorInt color: Int = Color.LTGRAY

) : ItemDecoration() {

    private val mDrawable = ColorDrawable(color)

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        // 第一个ItemView不需要在上面绘制分割线
        if (parent.getChildLayoutPosition(view) != 0) {
            outRect.top = dividerHeight
        }
    }

    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        val left: Int = parent.paddingLeft + leftMargin
        val right: Int = parent.width - parent.paddingRight - rightMargin
        val childCount: Int = parent.childCount
        for (i in 0 until childCount) {
            //第一个ItemView不需要绘制
            if (i == 0) {
                continue
            }
            val child: View = parent.getChildAt(i)
            val params = child.layoutParams as RecyclerView.LayoutParams
            val top = child.top + params.bottomMargin
            val bottom = top + dividerHeight
            mDrawable.setBounds(left, top, right, bottom)
            mDrawable.draw(c)
        }
    }
}