package com.adealink.weparty.module.widget.form.dialog

import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.util.onClick
import com.adealink.weparty.R
import com.adealink.weparty.commonui.ext.gone
import com.adealink.weparty.commonui.ext.show
import com.adealink.weparty.commonui.widget.BottomDialogFragment
import com.adealink.weparty.databinding.WidgetDialogSingleChooseBinding
import com.adealink.weparty.module.widget.form.data.StepFieldConstant

data class SingleChooseItem(
    val option: StepFieldConstant
) : ChooseItem() {
    override fun getDisplayName(): String {
        return option.value
    }

}

fun SingleChooseItem?.sameWith(other: SingleChooseItem?): Boolean {
    if (this == null && other == null) {
        return true
    }
    return this?.option?.key == other?.option?.key
            && this?.option?.value == other?.option?.value
}

class SingleChoiceDialog : BottomDialogFragment(R.layout.widget_dialog_single_choose) {

    private val binding by viewBinding(WidgetDialogSingleChooseBinding::bind)

    private var title: String? = null
    private var desc: String? = null
    private var chooseItemList = listOf<SingleChooseItem>()
    private var callback: IChooseCallback? = null


    fun setTitle(title: String?) {
        this.title = title
    }

    fun setDesc(desc: String?) {
        this.desc = desc
    }

    fun setItemList(chooseItemList: List<SingleChooseItem>?) {
        this.chooseItemList = chooseItemList ?: emptyList()
    }

    fun setCallback(callback: IChooseCallback) {
        this.callback = callback
    }

    override fun initViews() {
        super.initViews()
        if (title.isNullOrEmpty()) {
            binding.tvTitle.gone()
        } else {
            binding.tvTitle.show()
            binding.tvTitle.text = title
        }

        if (desc.isNullOrEmpty()) {
            binding.tvDesc.gone()
        } else {
            binding.tvDesc.show()
            binding.tvDesc.text = desc
        }

        val selectIndex = chooseItemList.indexOfFirst { it.selected }
        binding.vChoice.setEntries(
            chooseItemList.map {
                it.getDisplayName()
            },
            if (selectIndex == -1) {
                0
            } else {
                selectIndex
            }
        )
        binding.btnConfirm.onClick {
            confirm()
        }
    }

    private fun confirm() {
        val item = chooseItemList.getOrNull(binding.vChoice.currentIndex)
        callback?.onChoose(item)
        dismiss()
    }

    interface IChooseCallback {
        fun onChoose(items: SingleChooseItem?)
    }

}