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

import android.text.InputFilter
import android.text.InputType
import android.view.Gravity
import android.view.View
import androidx.databinding.BindingAdapter
import androidx.databinding.InverseBindingAdapter
import androidx.databinding.InverseBindingListener
import com.lukouguoji.module_base.ktx.loge
import com.lukouguoji.module_base.ui.weight.search.layout.PadSearchLayout
import dev.utils.app.EditTextUtils
import dev.utils.app.SizeUtils
import dev.utils.app.ViewUtils
import dev.utils.app.info.KeyValue

@BindingAdapter(
    "type",
    "title",
    "titleLength",
    "hint",
    "required",
    "icon",
    requireAll = false
)
fun setDataLayoutData(
    dataLayout: PadDataLayout,
    type: DataLayoutType?,
    title: String?,
    titleLength: Int?,
    hint: String?,
    required: Boolean?,
    icon: Any?,
) {
    type?.let {
        dataLayout.type = it
    }
    title?.let {
        dataLayout.tvTitle.text = title
    }
    titleLength?.let {
        dataLayout.titleLength = titleLength
    }
    required?.let {
        dataLayout.required = it
    }
    hint?.let {
        dataLayout.hint = hint
    }
    icon?.let {
        dataLayout.icon = it
    }
}


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

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

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

@BindingAdapter(
    "inputHeight",
    requireAll = false
)
fun setSearchLayoutInputHeight(
    layout: PadDataLayout,
    inputHeight: Int?,
) {
    inputHeight?.let {
        ViewUtils.setHeight(layout.llContainer, SizeUtils.dp2px(it.toFloat()))
        layout.et.setRawInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE)
        layout.et.gravity = Gravity.TOP
        layout.et.isSingleLine = false
        layout.et.isHorizontalScrollBarEnabled = false
        ViewUtils.setPadding(layout.et, SizeUtils.dp2px(10f))
    }
}

/**
 * 设置最大长度
 * 仅对Input类型有效
 */
@BindingAdapter(
    "maxLength",
    requireAll = false
)
fun setSearchLayoutMaxLength(
    layout: PadDataLayout,
    maxLength: Int?,
) {
    maxLength?.let {
        EditTextUtils.setMaxLength(layout.et, maxLength)
    }
}

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

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

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

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

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

// ========== PadDataLayoutNew BindingAdapters ==========

@BindingAdapter(
    "type",
    "title",
    "titleLength",
    "hint",
    "required",
    "icon",
    requireAll = false
)
fun setDataLayoutDataNew(
    dataLayout: PadDataLayoutNew,
    type: DataLayoutType?,
    title: String?,
    titleLength: Int?,
    hint: String?,
    required: Boolean?,
    icon: Any?,
) {
    type?.let {
        dataLayout.type = it
    }
    title?.let {
        dataLayout.tvTitle.text = title
    }
    titleLength?.let {
        dataLayout.titleLength = titleLength
    }
    required?.let {
        dataLayout.required = it
    }
    hint?.let {
        dataLayout.hint = hint
    }
    icon?.let {
        dataLayout.icon = it
    }
}


@BindingAdapter(
    "value",
    requireAll = false
)
fun setSearchLayoutDataValueNew(
    layout: PadDataLayoutNew,
    value: String?,
) {
    value?.let {
        layout.value = value
    }
}
@BindingAdapter(
    "enable",
    requireAll = false
)
fun setSearchLayoutDataEnableNew(
    layout: PadDataLayoutNew,
    enable: Boolean?,
) {
    enable?.let {
        layout.enable = enable
    }
}

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

@BindingAdapter(
    "inputHeight",
    requireAll = false
)
fun setSearchLayoutInputHeightNew(
    layout: PadDataLayoutNew,
    inputHeight: Int?,
) {
    inputHeight?.let {
        ViewUtils.setHeight(layout.llContainer, SizeUtils.dp2px(it.toFloat()))
        layout.et.setRawInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE)
        layout.et.gravity = Gravity.TOP
        layout.et.isSingleLine = false
        layout.et.isHorizontalScrollBarEnabled = false
        ViewUtils.setPadding(layout.et, SizeUtils.dp2px(10f))
    }
}

/**
 * 设置最大长度
 * 仅对Input类型有效
 */
@BindingAdapter(
    "maxLength",
    requireAll = false
)
fun setSearchLayoutMaxLengthNew(
    layout: PadDataLayoutNew,
    maxLength: Int?,
) {
    maxLength?.let {
        EditTextUtils.setMaxLength(layout.et, maxLength)
    }
}

@InverseBindingAdapter(attribute = "value", event = "valueAttrChanged")
fun getDataLayoutValueNew(dataLayout: PadDataLayoutNew): String {
    return dataLayout.value
}

@BindingAdapter("valueAttrChanged", requireAll = false)
fun setDataLayoutValueAttrChangedNew(dataLayout: PadDataLayoutNew, listener: InverseBindingListener) {
    dataLayout.onChangeListener = listener
}

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

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

@BindingAdapter("setTextAllCaps", requireAll = false)
fun setTextAllCapsNew(layout: PadDataLayoutNew, textAllCaps: Boolean) {
    if (textAllCaps) {
        layout.et.filters = arrayOf<InputFilter>(InputFilter.AllCaps())
    } else {
        layout.et.filters = emptyArray<InputFilter>()
    }
}
// ========== 自动查询功能 BindingAdapter（新增） ==========

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

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

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

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

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

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

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

/**
 * 统一配置自动查询（所有属性设置完成后调用）
 *
 * ⚠️ 重要：必须在所有 autoQuery* 属性之后绑定，使用 requireAll = false
 */
@BindingAdapter(
    "autoQueryEnabled",
    "autoQueryUrl",
    "autoQueryParamKey",
    "autoQueryMinLength",
    "autoQueryMaxLength",
    "autoQueryTitle",
    "autoQueryDebounce",
    requireAll = false
)
fun configureAutoQuery(
    layout: PadDataLayoutNew,
    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)
    }
}
