package com.rdiot.yx485.device

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.rdiot.yx485.bean.ConsumableBean
import com.rdiot.yx485.databinding.ItemDeviceHeaderBinding

class DeviceAdapter(
    private val listener: ConsumableActionListener
) : RecyclerView.Adapter<DeviceAdapter.DeviceViewHolder>() {

    private var devices = mutableListOf<ConsumableBean.DeviceInfo>()

    fun submitList(newDevices: List<ConsumableBean.DeviceInfo>) {
        devices.clear()
        devices.addAll(newDevices)
        notifyDataSetChanged()
    }

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

    override fun onBindViewHolder(holder: DeviceViewHolder, position: Int) {
        holder.setIsRecyclable(false)
        holder.bind(devices[position])
    }

    override fun getItemCount() = devices.size

    inner class DeviceViewHolder(
        private val binding: ItemDeviceHeaderBinding
    ) : RecyclerView.ViewHolder(binding.root) {

        fun bind(device: ConsumableBean.DeviceInfo) {
            binding.apply {
                tvDeviceName.text = device.device_name
                tvDeviceType.text = device.device_type_name
                if (device.consumables.isEmpty()) {
                    divider.visibility = View.GONE
                } else {
                    divider.visibility = View.VISIBLE
                }

                // 设置耗材列表
                val consumableAdapter = ConsumableAdapter(listener)
                rvConsumables.layoutManager = LinearLayoutManager(binding.root.context)
                rvConsumables.adapter = consumableAdapter
                consumableAdapter.submitList(device.consumables)
            }
        }
    }
} 