package com.yidian.shenghuoquan.buserorder.adapter

import android.graphics.Rect
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.yidian.shenghuoquan.buserorder.R
import com.yidian.shenghuoquan.buserorder.databinding.BorderItemPickupPointListBinding
import com.yidian.shenghuoquan.buserorder.dto.PickupPoint
import com.yidian.shenghuoquan.buserorder.viewmodel.PickupPointListItemViewModel
import com.yidian.utils.DensityUtil

/**
 * author: yinjiacheng
 * date: 2021/8/24 16:57
 * description: 自提点列表
 */
class PickupPointListAdapter(data: List<PickupPoint>?) : RecyclerView.Adapter<PickupPointListAdapter.PickupPointListViewHolder>() {

  private val data by lazy { ArrayList<PickupPoint>() }
  private var curSelectId = 0L
  private var location = false

  init {
    data?.let {
      this.data.addAll(it)
    }
  }

  /**
   * 更新数据
   */
  fun updateData(data: List<PickupPoint>?) {
    data?.let {
      notifyItemRangeRemoved(0, this.data.size)
      this.data.clear()
      this.data.addAll(it)
      notifyItemRangeInserted(0, this.data.size)
    }
  }

  /**
   * 设置当前选中的自提点id 默认0
   */
  fun setSelectedId(id: Long?) {
    curSelectId = id ?: 0
  }

  /**
   * 设置是否有位置信息
   */
  fun setLocation(location: Boolean) {
    this.location = location
  }

  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PickupPointListViewHolder {
    val binding = DataBindingUtil.inflate<BorderItemPickupPointListBinding>(
      LayoutInflater.from(parent.context),
      R.layout.border_item_pickup_point_list,
      parent,
      false
    )
    return PickupPointListViewHolder(binding.root, binding)
  }

  override fun onBindViewHolder(holder: PickupPointListViewHolder, position: Int) {
    holder.binding.vm = PickupPointListItemViewModel()
    holder.binding.data = data[position]
    holder.binding.selectedId = curSelectId
    holder.binding.location = location
  }

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

  class PickupPointListViewHolder(itemView: View, val binding: BorderItemPickupPointListBinding) : RecyclerView.ViewHolder(itemView)

  class PickupPointListItemDecoration : RecyclerView.ItemDecoration() {
    override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
      outRect.top = DensityUtil.dp2px(28F)
    }
  }

}

