package com.adealink.weparty.order.dialog

import android.annotation.SuppressLint
import android.text.Editable
import android.text.TextWatcher
import com.adealink.frame.mvvm.view.viewBinding
import com.adealink.frame.util.onClick
import com.adealink.weparty.commonui.text.setMaxLength
import com.adealink.weparty.commonui.widget.BottomDialogFragment
import com.adealink.weparty.constant.ORDER_REMARK_MAX_LENGTH
import com.adealink.weparty.order.R
import com.adealink.weparty.order.databinding.DialogEditRemarkBinding
import com.adealink.weparty.util.QMUIKeyboardHelper

class EditRemarkDialog : BottomDialogFragment(R.layout.dialog_edit_remark) {

    private val binding by viewBinding(DialogEditRemarkBinding::bind)
    private var callback: IEditRemarkCallback? = null

    private var remark: String? = null

    fun setCallback(callback: IEditRemarkCallback?) {
        this.callback = callback
    }

    fun setRemark(remark: String?) {
        this.remark = remark
    }

    @SuppressLint("SetTextI18n")
    override fun initViews() {
        super.initViews()
        binding.etInput.setMaxLength(ORDER_REMARK_MAX_LENGTH)
        binding.etInput.setText(remark)
        binding.etInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(
                s: CharSequence?,
                start: Int,
                count: Int,
                after: Int
            ) {
            }

            override fun onTextChanged(
                s: CharSequence?,
                start: Int,
                before: Int,
                count: Int
            ) {
            }

            override fun afterTextChanged(s: Editable?) {
                val length = s?.length ?: 0
                binding.tvInputCount.text = "${length}/${ORDER_REMARK_MAX_LENGTH}"
            }
        })
        binding.tvInputCount.text =
            "${binding.etInput.text?.length ?: 0}/${ORDER_REMARK_MAX_LENGTH}"
        binding.btnSave.onClick {
            save()
        }
        QMUIKeyboardHelper.showKeyboard(binding.etInput, true)
        binding.etInput.requestFocus()
    }

    private fun save() {
        val intro = binding.etInput.text?.toString()?.trim()
        callback?.onEditRemark(intro)
        dismiss()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        binding.etInput.clearFocus()
        QMUIKeyboardHelper.hideKeyboard(binding.etInput)
    }


    interface IEditRemarkCallback {
        fun onEditRemark(remark: String?)
    }


}