package com.dlc.chemical.ui.unlock

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.DialogSelectLockBinding
import com.dlc.chemical.databinding.ItemCabinetLockBinding
import com.dlc.chemical.ui.widget.flowlayout.FlowLayout
import com.dlc.chemical.ui.widget.flowlayout.TagAdapter
import com.rc.httpcore.vo.response.CabinetLockVo

/**
 * info
 *
 * @author ReiChin_
 */
class SelectCabinetLockDialog(
    context: Context,
    private val cabinetName: String?,
    private val datas: MutableList<CabinetLockVo>,
    private val callback: (cLockVo: CabinetLockVo) -> Unit
) :
    Dialog(context, R.style.AlertDialogStyle) {

    private val viewBinding: DialogSelectLockBinding by lazy {
        DialogSelectLockBinding.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.title.text = cabinetName
        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()
        }

        val adapter = CabinetLockAdapter(datas)
        viewBinding.cabinetFlow.adapter = adapter
    }
}

private class CabinetLockAdapter(
    datas: List<CabinetLockVo>
) :
    TagAdapter<CabinetLockVo>(datas) {

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

}