package xn.hxp.ui.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import xn.hxp.R


class CustomSpinnerTwoAdapter(private val ct: Context, private val dataList: List<String>?) :
    BaseAdapter() {

    // 修复1：处理数据源可能为null的情况
    override fun getCount(): Int = dataList?.size ?: 0

    // 修复2：避免空数据时getItem崩溃
    override fun getItem(position: Int): Any =
        dataList?.getOrNull(position) ?: "" // 空数据返回安全值

    override fun getItemId(position: Int): Long = position.toLong()

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val view = convertView ?: LayoutInflater.from(ct).inflate(
            R.layout.custom_spinner_item,
            parent,
            false
        ).apply {
            tag = ViewHolder(this) // 直接初始化ViewHolder
        }

        val viewHolder = view.tag as ViewHolder
        val item = getItem(position) as String

        viewHolder.line.visibility =
            if (position == (dataList?.size ?: 0) - 1) View.GONE
            else View.VISIBLE

        viewHolder.textView.text = item
        return view
    }

    private class ViewHolder(view: View) {
        val textView: TextView = view.findViewById(R.id.spinnerItemText)
        val line: View = view.findViewById(R.id.line)
    }
}