package adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.RecyclerView
import com.ydl.ydl_image.manager.YDLImageCacheManager
import com.yidianling.article.R
import data.ArticleBean

class ArticleHomeItemAdapter(private val mContext:Context):RecyclerView.Adapter<ArticleHomeItemAdapter.ArticleViewHolder>() {

    private var mData = mutableListOf<ArticleBean>()

    private var mListener:OnItemClickListener?=null

    fun setOnItemClickListener(listener: OnItemClickListener){
        mListener = listener
    }

    fun setData(data:MutableList<ArticleBean>){
        mData.clear()
        mData.addAll(data)
        notifyDataSetChanged()
    }

    fun addData(data:MutableList<ArticleBean>){
        mData.addAll(data)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, position: Int): ArticleViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.article_home_item_layout,parent,false)
        return ArticleViewHolder(view)
    }

    override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) {

        holder.tvTitle.text = mData[position].title
        holder.tvDesc.text = mData[position].desc
        holder.tvAuthorName.text = mData[position].name
        holder.tvArticleViewNum.text = "${mData[position].readNum}浏览"
        holder.tvArticleLikeNum.text = "${mData[position].zanNum}点赞"

        YDLImageCacheManager.showImage(mContext, mData[position]?.imgUrl, holder.ivArticleImage)
        YDLImageCacheManager.showImage(mContext, mData[position]?.smallImage, holder.ivAuthorAvatar)

        holder.itemView.setOnClickListener {
            mListener?.onItemClick(mData[position])
        }

    }

    override fun getItemCount(): Int {
        return mData.size
    }

    inner class ArticleViewHolder(itemView:View):RecyclerView.ViewHolder(itemView){
        var tvTitle:AppCompatTextView = itemView.findViewById(R.id.tv_article_title)
        var tvDesc:AppCompatTextView = itemView.findViewById(R.id.tv_article_desc)
        var ivArticleImage:AppCompatImageView = itemView.findViewById(R.id.iv_article_image)
        var ivAuthorAvatar:AppCompatImageView = itemView.findViewById(R.id.iv_author_avatar)
        var tvAuthorName:AppCompatTextView = itemView.findViewById(R.id.tv_author_name)
        var tvArticleViewNum:AppCompatTextView = itemView.findViewById(R.id.tv_article_view_num)
        var tvArticleLikeNum:AppCompatTextView = itemView.findViewById(R.id.tv_article_like_num)
    }

    interface OnItemClickListener{
        fun onItemClick(articleBean: ArticleBean)
    }


}