package com.yidian.shenghuoquan.newscontent.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.yidian.common.http.bean.GetCommonConfigBean
import com.yidian.shenghuoquan.newscontent.databinding.ItemMerchantServiceFunctionBinding

/**
 * author: yinjiacheng
 * date: 6/9/21 10:36 AM
 * description: 商户服务adapter
 */
class MerchantServiceFunctionAdapter @JvmOverloads constructor(
  val context: Context,
  data: List<GetCommonConfigBean.Function>? = null,
  val listener: OnItemClickListener? = null
) :
  RecyclerView.Adapter<MerchantServiceFunctionAdapter.MerchantServiceViewHolder>() {

  companion object {
    // 是否显示标识
    private const val FUNCTION_SHOW = 1
  }

  /**
   * 数据源
   */
  private val serviceData by lazy { ArrayList<GetCommonConfigBean.Function>() }

  private lateinit var viewBinding: ItemMerchantServiceFunctionBinding

  init {
    data?.let {
      it.forEach { item ->
        if (item.show == FUNCTION_SHOW) {
          serviceData.add(item)
        }
      }
    }
  }

  /**
   * 更新数据 将不显示的数据去除
   */
  fun updateData(data: List<GetCommonConfigBean.Function>?) {
    data?.let {
      serviceData.clear()
      it.forEach { item ->
        if (item.show == FUNCTION_SHOW) {
          serviceData.add(item)
        }
      }
      notifyDataSetChanged()
    }
  }

  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MerchantServiceViewHolder {
    viewBinding = ItemMerchantServiceFunctionBinding.inflate(
      LayoutInflater.from(
        parent.context
      ), parent, false
    )
    return MerchantServiceViewHolder(viewBinding.root, viewBinding)
  }

  override fun onBindViewHolder(holder: MerchantServiceViewHolder, position: Int) {
    val data = serviceData[position]
    if (data.iconUrl.isNotEmpty()) {
      Glide.with(context).load(data.iconUrl).into(viewBinding.ivService)
    } else {
      // TODO: 6/11/21 显示本地icon
    }
    holder.viewBinding.tvService.text = data.functionName
    holder.viewBinding.root.setOnClickListener { listener?.onItemClick(it, position, data) }
  }

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

  class MerchantServiceViewHolder(
    itemView: View,
    val viewBinding: ItemMerchantServiceFunctionBinding
  ) :
    RecyclerView.ViewHolder(itemView)

  interface OnItemClickListener {
    fun onItemClick(view: View, position: Int, data: GetCommonConfigBean.Function)
  }

}
