package com.yidian.shenghuoquan.newscontent.adapter

import android.content.Context
import android.graphics.Rect
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.yidian.shenghuoquan.newscontent.databinding.ItemMerchantServiceGroupBinding
import com.yidian.shenghuoquan.newscontent.http.httpbean.GetConfigListBean
import com.yidian.utils.DensityUtil

/**
 * author: yinjiacheng
 * date: 6/11/21 10:21 AM
 * description: 商户服务分组adapter
 */
class MerchantServiceGroupAdapter @JvmOverloads constructor(
  val context: Context,
  data: List<GetConfigListBean.Item>? = null,
  val listener: MerchantServiceFunctionAdapter.OnItemClickListener? = null
) :
  RecyclerView.Adapter<MerchantServiceGroupAdapter.MerchantServiceGroupViewHolder>() {

  companion object {
    // 是否显示标识(1：显示；0：不显示)
    private const val GROUP_SHOW = 1
  }

  private lateinit var viewBinding: ItemMerchantServiceGroupBinding

  /**
   * 数据源
   */
  private val groupData by lazy {
    ArrayList<GetConfigListBean.Item>()
  }

  init {
    // 将不显示的数据去除
    data?.let {
      it.forEach { item ->
        if (item.show == GROUP_SHOW) {
          groupData.add(item)
        }
      }
    }
  }

  /**
   * 刷新数据
   */
  fun updateData(data: List<GetConfigListBean.Item>?) {
    groupData.clear()
    data?.let {
      it.forEach { item ->
        if (item.show == GROUP_SHOW) {
          groupData.add(item)
        }
      }
    }
    notifyDataSetChanged()
  }

  override fun onCreateViewHolder(
    parent: ViewGroup,
    viewType: Int
  ): MerchantServiceGroupViewHolder {
    viewBinding =
      ItemMerchantServiceGroupBinding.inflate(
        LayoutInflater.from(parent.context),
        parent,
        false
      )
    val holder = MerchantServiceGroupViewHolder(viewBinding.root, viewBinding)
    // ViewHolder禁止复用
    holder.setIsRecyclable(false)
    return holder
  }

  override fun onBindViewHolder(holder: MerchantServiceGroupViewHolder, position: Int) {
    val data = groupData[position]
    holder.viewBinding.tvTitle.text = data.group_name
    viewBinding.rvService.layoutManager = GridLayoutManager(context, 4)
    viewBinding.rvService.adapter = MerchantServiceFunctionAdapter(context, data.functions, listener)
  }

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

  class MerchantServiceGroupViewHolder(
    itemView: View,
    val viewBinding: ItemMerchantServiceGroupBinding
  ) : RecyclerView.ViewHolder(itemView)

  /**
   * 管理中心菜单列表的分割线
   */
  class MerchantServiceGroupItemDecorator : RecyclerView.ItemDecoration() {
    override fun getItemOffsets(
      outRect: Rect,
      view: View,
      parent: RecyclerView,
      state: RecyclerView.State
    ) {
      outRect.bottom = DensityUtil.dp2px(10f)
    }
  }

}
