package com.sd.cavphmi.ui.view

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.sd.cavphmi.R

class CustomListDialog(
    context: Context,
    private val title: String,
    private val dataList: List<String>
) : Dialog(context) {

    interface OnItemClickListener {
        fun onItemClick(position: Int, selectedItem: String)
    }

    private var itemClickListener: OnItemClickListener? = null

    // 3. 设置监听器的方法
    fun setOnItemClickListener(listener: OnItemClickListener) {
        this.itemClickListener = listener
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dialog_custom)

        window?.setBackgroundDrawableResource(android.R.color.transparent)
        window?.setLayout(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )

        findViewById<TextView>(R.id.title).text = title
        findViewById<TextView>(R.id.tv_cancle).setOnClickListener{
            dismiss()
        }

        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)
        recyclerView.layoutManager = LinearLayoutManager(context)
        val adapter = SimpleAdapter(dataList) { position, item ->
            itemClickListener?.onItemClick(position, item)
            dismiss()
        }
        recyclerView.adapter = adapter
    }

    class SimpleAdapter(
        private val items: List<String>,
        private val onItemClick: (Int, String) -> Unit
    ) : RecyclerView.Adapter<SimpleAdapter.ViewHolder>() {

        inner class ViewHolder(val view: View) : RecyclerView.ViewHolder(view)

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.item_car, parent, false)
            return ViewHolder(view)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val textView=holder.view.findViewById<TextView>(R.id.tv_car)
            textView.text = items[position]
            textView.setOnClickListener {
                onItemClick(position, items[position])
            }
        }

        override fun getItemCount() = items.size
    }
}