package com.lukouguoji.module_base.adapter

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.TextView
import androidx.databinding.BindingAdapter
import com.lukouguoji.module_base.R
import com.lukouguoji.module_base.interfaces.IOnSpinnerSelected
import dev.utils.app.info.KeyValue
import dev.utils.common.ReflectUtils

class SpinnerHintAdapter<T>(context: Context, resource: Int, objects: List<T>) :
    ArrayAdapter<T>(context, resource, objects) {

    override fun getCount(): Int {
        val count = super.getCount()
        return if (count == 0) 0 else count - 1
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view = super.getView(position, convertView, parent)
        (view as TextView).setTextColor(
            if (position == count) {
                context.resources.getColor(R.color.text_gray_l)
            } else {
                context.resources.getColor(R.color.text_normal)
            }
        )
        return view
    }
}

@BindingAdapter("items", "hint", "itemId", requireAll = false)
fun bindAdapter(
    spinner: Spinner,
    items: List<KeyValue>?,
    hint: String? = null,
    itemId: Int? = null
) {
    val layoutId = itemId ?: R.layout.item_spinner_list
    if (items == null && hint.isNullOrEmpty()) {
        return
    }
    val list = items?.map { it.key } ?: listOf()
    if (hint.isNullOrEmpty()) {
        val adapter = ArrayAdapter(spinner.context, layoutId, list)
        spinner.adapter = adapter
    } else if (list.isEmpty()) {
        // 列表为空时：控件上显示 hint 占位文字（灰色），下拉列表隐藏
        // 不能用 SpinnerHintAdapter，其 getCount()=0 会导致 Spinner 不渲染
        val adapter = object : ArrayAdapter<String>(spinner.context, layoutId, listOf(hint)) {
            override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
                val view = super.getView(position, convertView, parent)
                (view as TextView).setTextColor(context.resources.getColor(R.color.text_gray_l))
                return view
            }

            override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
                // 下拉列表中隐藏 hint 项
                val view = super.getDropDownView(position, convertView, parent)
                view.visibility = View.GONE
                view.layoutParams = ViewGroup.LayoutParams(0, 0)
                return view
            }
        }
        spinner.adapter = adapter
        spinner.setSelection(0)
    } else {
        val containHintList = list + hint
        val adapter = SpinnerHintAdapter(spinner.context, layoutId, containHintList)
        spinner.adapter = adapter
        spinner.setSelection(list.size)
    }
}

@BindingAdapter("setEnable")
fun setEnable(view: View, enabled: Boolean) {
    view.isEnabled = enabled
}

@BindingAdapter("selectedItem")
fun setSelectedItem(spinner: Spinner, item: String) {
    spinner.adapter?.let {
        val list = ReflectUtils.reflect(it).field("mObjects").get() as List<String>
        val index = list.indexOf(item)
        if (index >= 0) {
            spinner.setSelection(index)
        }
    }
}

@BindingAdapter("onSelected")
fun bindOnSelected(spinner: Spinner, selectedListener: IOnSpinnerSelected) {
    spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onItemSelected(
            parent: AdapterView<*>?,
            view: View?,
            position: Int,
            id: Long
        ) {
            selectedListener.onSelected(position)
        }

        override fun onNothingSelected(parent: AdapterView<*>?) {
        }
    }
}
