package com.dlc.chemical.ui.query

import android.app.Dialog
import android.content.Context
import android.content.res.Resources
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import com.dlc.chemical.R
import com.dlc.chemical.databinding.DialogSelectCabinetBinding
import com.dlc.chemical.databinding.ItemCabinetBinding
import com.dlc.chemical.ui.widget.flowlayout.FlowLayout
import com.dlc.chemical.ui.widget.flowlayout.TagAdapter
import com.rc.httpcore.vo.response.CabinetBean

/**
 * 选择机柜dialog
 *
 * @author ReiChin_
 */
class SelectCabinetDialog(
    context: Context,
    private val datas: MutableList<CabinetBean>,
    private val selectedBean: CabinetBean,
    private val callback: (cBean: CabinetBean) -> Unit
) :
    Dialog(context, R.style.AlertDialogStyle) {

    private val viewBinding: DialogSelectCabinetBinding by lazy {
        DialogSelectCabinetBinding.inflate(LayoutInflater.from(context))
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(viewBinding.root)
        initWindowConfig()
        initViews()
    }

    private fun initWindowConfig() {
        window?.apply {
            val dm = Resources.getSystem().displayMetrics
            attributes.width = (dm.widthPixels * 0.5f).toInt()
            attributes.height = WindowManager.LayoutParams.WRAP_CONTENT
        }
    }

    private fun initViews() {
        viewBinding.cancel.setOnClickListener { dismiss() }
        viewBinding.confirm.setOnClickListener {
            val selectedItems = viewBinding.cabinetFlow.selectedList
            if (selectedItems.isNullOrEmpty()) {
                Toast.makeText(context, "请选择机柜", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            val position = selectedItems.iterator().next()
            callback.invoke(datas[position])
            dismiss()
        }

        viewBinding.cabinetFlow.adapter = CabinetAdapter(datas, selectedBean)
    }

}

private class CabinetAdapter(
    datas: List<CabinetBean>,
    private val selectedBean: CabinetBean
) :
    TagAdapter<CabinetBean>(datas) {

    override fun getView(parent: FlowLayout?, position: Int, text: CabinetBean?): View {
        val binding = ItemCabinetBinding.inflate(LayoutInflater.from(parent!!.context))
        binding.textView.text = text?.cabinetName
        return binding.root
    }

    override fun setSelected(position: Int, t: CabinetBean?): Boolean {
        return selectedBean.id == t?.id
    }

}