package com.lukouguoji.module_base.base

import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView
import com.lukouguoji.module_base.interfaces.IOnItemClickListener
import kotlin.properties.Delegates

abstract class BaseViewHolder<T, B : ViewDataBinding>(itemView: View) :
    RecyclerView.ViewHolder(itemView) {

    //数据视图绑定器
    var binding: B by Delegates.notNull()

    // 点击事件
    var clickListener: IOnItemClickListener? = null

    /**
     * 初始化
     */
    open fun initOnCreate() {
        binding = DataBindingUtil.bind(itemView)!!
    }

    /**
     * 绑定数据
     */
    abstract fun onBind(item: Any?, position: Int)

    fun getItemBean(item: Any?): T? {
        return try {
            item as T
        } catch (e: Exception) {
            null
        }
    }

    /**
     * 获取RecyclerView
     */
    fun getRecyclerView(): RecyclerView? {
        var v: View = itemView
        var rv: RecyclerView? = null
        while (rv == null && v.parent != null) {
            val parent = v.parent as ViewGroup
            if (parent is RecyclerView) {
                rv = parent
            }
            v = parent
        }
        return rv
    }

    /**
     * 获取上下文对象
     */
    fun requireContext(): Context = itemView.context

    /**
     * 通知条目点击事件
     */
    fun notifyItemClick(position: Int, view: View) {
        view.setOnClickListener {
            clickListener?.onItemClick(bindingAdapterPosition, view.id)
        }
    }

}