package com.lukouguoji.module_base.ui.weight.search.layout

import android.graphics.drawable.Drawable
import android.text.InputFilter
import android.text.InputType
import android.view.View
import androidx.core.widget.doOnTextChanged
import androidx.databinding.BindingAdapter
import androidx.databinding.InverseBindingAdapter
import androidx.databinding.InverseBindingListener
import com.lukouguoji.module_base.ktx.UpperCaseAlphanumericInputFilter
import dev.utils.app.EditTextUtils
import dev.utils.app.info.KeyValue


@BindingAdapter(
    "type",
    "hint",
    "required",
    "icon",
    requireAll = false
)
fun setSearchLayoutData(
    layout: PadSearchLayout,
    type: SearchLayoutType?,
    hint: String?,
    required: Boolean?,
    icon: Any?,
) {
    type?.let {
        layout.type = type
    }
    required?.let {
        layout.required = required
    }
    hint?.let {
        layout.hint = hint
    }
    icon?.let {
        layout.icon = icon
    }
}

@BindingAdapter(
    "value",
    requireAll = false
)
fun setSearchLayoutDataValue(
    layout: PadSearchLayout,
    value: String?,
) {
    value?.let {
        layout.value = value
    }
}

@BindingAdapter(
    "enable",
    requireAll = false
)
fun setSearchLayoutDataEnable(
    layout: PadSearchLayout,
    enable: Boolean?,
) {
    enable?.let {
        layout.enable = enable
    }
}

@BindingAdapter(
    "list",
    requireAll = false
)
fun setSearchLayoutDataList(
    layout: PadSearchLayout,
    list: List<KeyValue>?,
) {
    list?.let {
        layout.list = list
    }
}

@BindingAdapter(
    "bgDrawable",
    requireAll = false
)
fun setSearchLayoutDataBackground(
    layout: PadSearchLayout,
    bgDrawable: Drawable,
) {
    layout.ll.setBackgroundDrawable(bgDrawable)
}

@InverseBindingAdapter(attribute = "value", event = "valueAttrChanged")
fun getDataLayoutValue(layout: PadSearchLayout): String {
    return layout.value
}

@BindingAdapter("valueAttrChanged", requireAll = false)
fun setDataLayoutValueAttrChanged(layout: PadSearchLayout, listener: InverseBindingListener) {
    layout.onChangeListener = listener
}

@BindingAdapter("setOnIconClickListener", requireAll = false)
fun setOnIconClickListener(layout: PadSearchLayout, listener: View.OnClickListener?) {
    layout.iv.setOnClickListener(listener)
}

@BindingAdapter("setRefreshCallBack", requireAll = false)
fun setRefreshCallBack(layout: PadSearchLayout, listener: (() -> Unit)?) {
    layout.refreshCallBack = listener
}

@BindingAdapter("setSearchListRefresh")
fun setListRefreshCallBack(layout: PadSearchLayout, listener: (() -> Unit)?) {
    layout.listRefreshCallBack = listener
}

@BindingAdapter("setTextAllCaps", requireAll = false)
fun setTextAllCaps(layout: PadSearchLayout, textAllCaps: Boolean) {
    if (textAllCaps) {
        layout.et.filters = arrayOf<InputFilter>(InputFilter.AllCaps())
    } else {
        layout.et.filters = emptyArray<InputFilter>()
    }
}

@BindingAdapter("setInputWaybill", requireAll = false)
fun setInputWaybill(layout: PadSearchLayout, isWaybill: Boolean) {
    if (isWaybill) {
        EditTextUtils.setMaxLength(layout.et, 11)
        EditTextUtils.setInputType(layout.et, InputType.TYPE_CLASS_NUMBER)
        layout.et.doOnTextChanged { text, _, _, _ ->
            if (text.toString().length == 11) {
                layout.refreshCallBack?.invoke()
            }
            if (text.toString().length in 4..8){
                layout.listRefreshCallBack?.invoke()
            }
        }
    }
}

/**
 * 设置搜索监听器（回车键或搜索按钮触发）
 */
@BindingAdapter("setOnSearchListener", requireAll = false)
fun setSearchLayoutNewOnSearchListener(layout: PadSearchLayoutNew, listener: (() -> Unit)?) {
    layout.searchCallBack = listener
}

/**
 * 设置搜索图标点击为搜索功能
 */
@BindingAdapter("setSearchIconClickListener", requireAll = false)
fun setSearchLayoutNewSearchIconClickListener(layout: PadSearchLayoutNew, listener: (() -> Unit)?) {
    layout.iv.setOnClickListener {
        listener?.invoke()
    }
}

///////////////////////////////////////////////////////////////////////////
// PadSearchLayoutNew 的绑定适配器
///////////////////////////////////////////////////////////////////////////

@BindingAdapter(
    "type",
    "hint",
    "required",
    "icon",
    requireAll = false
)
fun setSearchLayoutNewData(
    layout: PadSearchLayoutNew,
    type: SearchLayoutType?,
    hint: String?,
    required: Boolean?,
    icon: Any?,
) {
    type?.let {
        layout.type = type
    }
    required?.let {
        layout.required = required
    }
    hint?.let {
        layout.hint = hint
    }
    icon?.let {
        layout.icon = icon
    }
}

@BindingAdapter(
    "value",
    requireAll = false
)
fun setSearchLayoutNewDataValue(
    layout: PadSearchLayoutNew,
    value: String?,
) {
    value?.let {
        layout.value = value
    }
}

@BindingAdapter(
    "enable",
    requireAll = false
)
fun setSearchLayoutNewDataEnable(
    layout: PadSearchLayoutNew,
    enable: Boolean?,
) {
    enable?.let {
        layout.enable = enable
    }
}

@BindingAdapter(
    "list",
    requireAll = false
)
fun setSearchLayoutNewDataList(
    layout: PadSearchLayoutNew,
    list: List<KeyValue>?,
) {
    list?.let {
        layout.list = list
    }
}

@BindingAdapter(
    "bgDrawable",
    requireAll = false
)
fun setSearchLayoutNewDataBackground(
    layout: PadSearchLayoutNew,
    bgDrawable: Drawable,
) {
    layout.ll.setBackgroundDrawable(bgDrawable)
}

@InverseBindingAdapter(attribute = "value", event = "valueAttrChanged")
fun getSearchLayoutNewValue(layout: PadSearchLayoutNew): String {
    return layout.value
}

@BindingAdapter("valueAttrChanged", requireAll = false)
fun setSearchLayoutNewValueAttrChanged(layout: PadSearchLayoutNew, listener: InverseBindingListener) {
    layout.onChangeListener = listener
}

@BindingAdapter("setOnIconClickListener", requireAll = false)
fun setSearchLayoutNewOnIconClickListener(layout: PadSearchLayoutNew, listener: View.OnClickListener?) {
    layout.iv.setOnClickListener(listener)
}

@BindingAdapter("setRefreshCallBack", requireAll = false)
fun setSearchLayoutNewRefreshCallBack(layout: PadSearchLayoutNew, listener: (() -> Unit)?) {
    layout.refreshCallBack = listener
}

@BindingAdapter("setSearchListRefresh")
fun setSearchLayoutNewListRefreshCallBack(layout: PadSearchLayoutNew, listener: (() -> Unit)?) {
    layout.listRefreshCallBack = listener
}

@BindingAdapter("setTextAllCaps", requireAll = false)
fun setSearchLayoutNewTextAllCaps(layout: PadSearchLayoutNew, textAllCaps: Boolean) {
    if (textAllCaps) {
        layout.et.filters = arrayOf<InputFilter>(InputFilter.AllCaps())
    } else {
        layout.et.filters = emptyArray<InputFilter>()
    }
}

@BindingAdapter("setInputWaybill", requireAll = false)
fun setSearchLayoutNewInputWaybill(layout: PadSearchLayoutNew, isWaybill: Boolean) {
    if (isWaybill) {
        EditTextUtils.setMaxLength(layout.et, 11)
        EditTextUtils.setInputType(layout.et, InputType.TYPE_CLASS_NUMBER)
        layout.et.doOnTextChanged { text, _, _, _ ->
            if (text.toString().length == 11) {
                layout.refreshCallBack?.invoke()
            }
            if (text.toString().length in 4..8){
                layout.listRefreshCallBack?.invoke()
            }
        }
    }
}

///////////////////////////////////////////////////////////////////////////
// 大写字母+数字输入限制 BindingAdapter
///////////////////////////////////////////////////////////////////////////

/**
 * 为PadSearchLayout设置大写字母+数字输入限制
 * 自动转换小写为大写，过滤中文、特殊符号、空格
 */
@BindingAdapter("setUpperCaseAlphanumeric", requireAll = false)
fun setUpperCaseAlphanumeric(layout: PadSearchLayout, enabled: Boolean) {
    if (enabled) {
        layout.et.filters = arrayOf(UpperCaseAlphanumericInputFilter())
    }
}

///////////////////////////////////////////////////////////////////////////
// PadSearchLayout 自动查询功能 BindingAdapter
///////////////////////////////////////////////////////////////////////////

/**
 * 启用自动查询功能
 * @param enabled 是否启用
 */
@BindingAdapter("autoQueryEnabled")
fun setSearchLayoutAutoQueryEnabled(layout: PadSearchLayout, enabled: Boolean) {
    layout.autoQueryConfig.enabled = enabled
}

/**
 * 设置查询接口地址
 * @param url 接口地址（如：/IntExpCheckIn/queryWbNoList）
 */
@BindingAdapter("autoQueryUrl")
fun setSearchLayoutAutoQueryUrl(layout: PadSearchLayout, url: String?) {
    layout.autoQueryConfig.url = url ?: ""
}

/**
 * 设置查询参数的 key 名称
 * @param paramKey 参数名（默认 "value"）
 */
@BindingAdapter("autoQueryParamKey")
fun setSearchLayoutAutoQueryParamKey(layout: PadSearchLayout, paramKey: String?) {
    layout.autoQueryConfig.paramKey = paramKey ?: "value"
}

/**
 * 设置触发查询的最小长度
 * @param minLength 最小长度（默认 4）
 */
@BindingAdapter("autoQueryMinLength")
fun setSearchLayoutAutoQueryMinLength(layout: PadSearchLayout, minLength: Int?) {
    layout.autoQueryConfig.minLength = minLength ?: 4
}

/**
 * 设置触发查询的最大长度
 * @param maxLength 最大长度（默认 8）
 */
@BindingAdapter("autoQueryMaxLength")
fun setSearchLayoutAutoQueryMaxLength(layout: PadSearchLayout, maxLength: Int?) {
    layout.autoQueryConfig.maxLength = maxLength ?: 8
}

/**
 * 设置弹框标题
 * @param title 标题（默认 "请选择"）
 */
@BindingAdapter("autoQueryTitle")
fun setSearchLayoutAutoQueryTitle(layout: PadSearchLayout, title: String?) {
    layout.autoQueryConfig.title = title ?: "请选择"
}

/**
 * 设置防抖延迟
 * @param debounceMillis 延迟毫秒数（默认 300ms）
 */
@BindingAdapter("autoQueryDebounce")
fun setSearchLayoutAutoQueryDebounce(layout: PadSearchLayout, debounceMillis: Long?) {
    layout.autoQueryConfig.debounceMillis = debounceMillis ?: 300L
}

/**
 * 统一配置自动查询（所有属性设置完成后调用）
 *
 * ⚠️ 重要：必须在所有 autoQuery* 属性之后绑定，使用 requireAll = false
 */
@BindingAdapter(
    "autoQueryEnabled",
    "autoQueryUrl",
    "autoQueryParamKey",
    "autoQueryMinLength",
    "autoQueryMaxLength",
    "autoQueryTitle",
    "autoQueryDebounce",
    requireAll = false
)
fun configureSearchLayoutAutoQuery(
    layout: PadSearchLayout,
    enabled: Boolean?,
    url: String?,
    paramKey: String?,
    minLength: Int?,
    maxLength: Int?,
    title: String?,
    debounceMillis: Long?
) {
    // 应用所有配置
    enabled?.let { layout.autoQueryConfig.enabled = it }
    url?.let { layout.autoQueryConfig.url = it }
    paramKey?.let { layout.autoQueryConfig.paramKey = it }
    minLength?.let { layout.autoQueryConfig.minLength = it }
    maxLength?.let { layout.autoQueryConfig.maxLength = it }
    title?.let { layout.autoQueryConfig.title = it }
    debounceMillis?.let { layout.autoQueryConfig.debounceMillis = it }

    // 验证并启用自动查询
    if (layout.autoQueryConfig.isValid()) {
        layout.enableAutoQuery(layout.autoQueryConfig)
    }
}

/**
 * 为PadSearchLayoutNew设置大写字母+数字输入限制
 * 自动转换小写为大写，过滤中文、特殊符号、空格
 */
@BindingAdapter("setUpperCaseAlphanumeric", requireAll = false)
fun setSearchLayoutNewUpperCaseAlphanumeric(layout: PadSearchLayoutNew, enabled: Boolean) {
    if (enabled) {
        layout.et.filters = arrayOf(UpperCaseAlphanumericInputFilter())
    }
}

///////////////////////////////////////////////////////////////////////////
// PadSearchLayoutNew 自动查询功能 BindingAdapter
///////////////////////////////////////////////////////////////////////////

/**
 * 启用自动查询功能
 * @param enabled 是否启用
 */
@BindingAdapter("autoQueryEnabled")
fun setSearchLayoutNewAutoQueryEnabled(layout: PadSearchLayoutNew, enabled: Boolean) {
    layout.autoQueryConfig.enabled = enabled
}

/**
 * 设置查询接口地址
 * @param url 接口地址（如：/IntExpCheckIn/checked/queryWbNoList）
 */
@BindingAdapter("autoQueryUrl")
fun setSearchLayoutNewAutoQueryUrl(layout: PadSearchLayoutNew, url: String?) {
    layout.autoQueryConfig.url = url ?: ""
}

/**
 * 设置查询参数的 key 名称
 * @param paramKey 参数名（默认 "value"）
 */
@BindingAdapter("autoQueryParamKey")
fun setSearchLayoutNewAutoQueryParamKey(layout: PadSearchLayoutNew, paramKey: String?) {
    layout.autoQueryConfig.paramKey = paramKey ?: "value"
}

/**
 * 设置触发查询的最小长度
 * @param minLength 最小长度（默认 4）
 */
@BindingAdapter("autoQueryMinLength")
fun setSearchLayoutNewAutoQueryMinLength(layout: PadSearchLayoutNew, minLength: Int?) {
    layout.autoQueryConfig.minLength = minLength ?: 4
}

/**
 * 设置触发查询的最大长度
 * @param maxLength 最大长度（默认 8）
 */
@BindingAdapter("autoQueryMaxLength")
fun setSearchLayoutNewAutoQueryMaxLength(layout: PadSearchLayoutNew, maxLength: Int?) {
    layout.autoQueryConfig.maxLength = maxLength ?: 8
}

/**
 * 设置弹框标题
 * @param title 标题（默认 "请选择"）
 */
@BindingAdapter("autoQueryTitle")
fun setSearchLayoutNewAutoQueryTitle(layout: PadSearchLayoutNew, title: String?) {
    layout.autoQueryConfig.title = title ?: "请选择"
}

/**
 * 设置防抖延迟
 * @param debounceMillis 延迟毫秒数（默认 300ms）
 */
@BindingAdapter("autoQueryDebounce")
fun setSearchLayoutNewAutoQueryDebounce(layout: PadSearchLayoutNew, debounceMillis: Long?) {
    layout.autoQueryConfig.debounceMillis = debounceMillis ?: 300L
}

/**
 * 统一配置自动查询（所有属性设置完成后调用）
 *
 * ⚠️ 重要：必须在所有 autoQuery* 属性之后绑定，使用 requireAll = false
 */
@BindingAdapter(
    "autoQueryEnabled",
    "autoQueryUrl",
    "autoQueryParamKey",
    "autoQueryMinLength",
    "autoQueryMaxLength",
    "autoQueryTitle",
    "autoQueryDebounce",
    requireAll = false
)
fun configureSearchLayoutNewAutoQuery(
    layout: PadSearchLayoutNew,
    enabled: Boolean?,
    url: String?,
    paramKey: String?,
    minLength: Int?,
    maxLength: Int?,
    title: String?,
    debounceMillis: Long?
) {
    // 应用所有配置
    enabled?.let { layout.autoQueryConfig.enabled = it }
    url?.let { layout.autoQueryConfig.url = it }
    paramKey?.let { layout.autoQueryConfig.paramKey = it }
    minLength?.let { layout.autoQueryConfig.minLength = it }
    maxLength?.let { layout.autoQueryConfig.maxLength = it }
    title?.let { layout.autoQueryConfig.title = it }
    debounceMillis?.let { layout.autoQueryConfig.debounceMillis = it }

    // 验证并启用自动查询
    if (layout.autoQueryConfig.isValid()) {
        layout.enableAutoQuery(layout.autoQueryConfig)
    }
}
