package com.casic.br.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.casic.br.R
import com.casic.br.extensions.combineImagePath
import com.casic.br.extensions.diffDate
import com.casic.br.model.OtherDeviceListModel

/**
 * 汉威报警器Adapter
 * */
class OtherDeviceAdapter(
    private val context: Context,
    private val dataRows: MutableList<OtherDeviceListModel.DataModel.RowsModel>
) : RecyclerView.Adapter<OtherDeviceAdapter.ItemViewHolder>() {

    private var layoutInflater: LayoutInflater = LayoutInflater.from(context)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        return ItemViewHolder(
            layoutInflater.inflate(R.layout.item_other_device_rv_g, parent, false)
        )
    }

    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        val rowsModel = dataRows[position]
        holder.deviceNameView.text = rowsModel.deviceName
        Glide.with(context)
            .load(rowsModel.picUri.combineImagePath())
            .apply(RequestOptions.circleCropTransform())
            .placeholder(R.mipmap.load_image_error)
            .into(holder.imageView)
        holder.deviceModelView.text = rowsModel.productCode
        holder.deviceUsedTimeView.text = String.format(
            "已使用${rowsModel.createTime.toString().diffDate(true)}天"
        )
        holder.rootView.setOnClickListener {
            clickListener?.onItemClick(position)
        }
    }

    override fun getItemCount(): Int = dataRows.size

    private var clickListener: OnItemClickListener? = null

    interface OnItemClickListener {
        fun onItemClick(position: Int)
    }

    fun setOnItemClickListener(clickListener: OnItemClickListener?) {
        this.clickListener = clickListener
    }

    class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val rootView: LinearLayout = itemView.findViewById(R.id.rootView)
        val deviceNameView: TextView = itemView.findViewById(R.id.deviceNameView)
        val imageView: ImageView = itemView.findViewById(R.id.imageView)
        val deviceModelView: TextView = itemView.findViewById(R.id.deviceModelView)
        val deviceUsedTimeView: TextView = itemView.findViewById(R.id.deviceUsedTimeView)
    }
}