package com.rdiot.yx485.device

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.rdiot.yx485.R
import com.rdiot.yx485.bean.ConsumableBean
import com.rdiot.yx485.databinding.ItemConsumableBinding
import kotlin.math.roundToInt

class ConsumableAdapter(
    private val listener: ConsumableActionListener
) : RecyclerView.Adapter<ConsumableAdapter.ConsumableViewHolder>() {

    private var consumables = mutableListOf<ConsumableBean.ConsumableInfo>()

    fun submitList(newConsumables: List<ConsumableBean.ConsumableInfo>) {
        consumables.clear()
        consumables.addAll(newConsumables)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ConsumableViewHolder {
        val binding = ItemConsumableBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return ConsumableViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ConsumableViewHolder, position: Int) {
        holder.bind(consumables[position])
    }

    override fun getItemCount() = consumables.size

    inner class ConsumableViewHolder(
        private val binding: ItemConsumableBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        fun bind(consumable: ConsumableBean.ConsumableInfo) {
            binding.apply {
                tvConsumableName.text = consumable.consumable_name
                tvUsedDays.text = root.context.getString(
                    R.string.used_days_format,
                    consumable.used_time
                )

                val percentage = (consumable.user_rate * 100).roundToInt()
                progressIndicator.progress = percentage
                tvProgress.text = String.format("%s%%", percentage)

                val needsReplacement = consumable.user_rate >= 0.8
                btnAction.text = if (needsReplacement) "更换" else "重置"
                btnAction.setOnClickListener {
                    listener.onResetClick(consumable.record_id)
                }

                // 只在不是最后一个耗材时显示分割线
                divider.visibility = if (position == consumables.lastIndex) {
                    View.GONE
                } else {
                    View.VISIBLE
                }
            }
        }
    }
}