package com.adealink.weparty.commonui.text.filter

import android.text.InputFilter
import android.text.InputType
import android.widget.EditText

fun EditText.addDecimalInputFilter(
    maxIntegerDigits: Int = 10,
    maxDecimalDigits: Int = 2,
    maxValue: Double = Double.MAX_VALUE,
    onInputTooMax: (() -> Unit)? = null //输入过大回调
) {
    this.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL

    val filter = InputFilter { source, start, end, dest, dstart, dend ->
        if (end == 0) return@InputFilter null // 允许删除

        val newText = StringBuilder(dest).apply {
            replace(dstart, dend, source.subSequence(start, end).toString())
        }.toString()

        if (newText.isEmpty()) return@InputFilter null

        // 验证逻辑
        when {
            !newText.matches(Regex("[0-9.]*")) -> {
                //填入的不是数字,小数点
                ""
            }

            newText.startsWith(".") -> {
                //不能以小数点打头
                ""
            }

            newText.count { it == '.' } > 1 -> {
                //只能一个小数点
                ""
            }

            !isValidDecimalFormat(newText, maxIntegerDigits, maxDecimalDigits) -> {
                //数字不合法
                ""
            }

            !isWithinMaxValue(newText, maxValue) -> {
                //数字过大
                onInputTooMax?.invoke()
                ""
            }

            else -> null
        }
    }

    addFilter(filter)
}

private fun isValidDecimalFormat(text: String, maxInt: Int, maxDec: Int): Boolean {
    return when {
        text == "0" -> true
        text.matches(Regex("^0\\.[0-9]*$")) -> {
            val decimalPart = text.substringAfter(".")
            decimalPart.length <= maxDec
        }

        text.contains(".") -> {
            val parts = text.split(".")
            if (parts.size != 2) return false

            val integerPart = parts[0]
            val decimalPart = parts[1]

            integerPart.matches(Regex("[1-9][0-9]*")) &&
                    integerPart.length <= maxInt &&
                    decimalPart.length <= maxDec
        }

        else -> {
            text.matches(Regex("[1-9][0-9]*")) && text.length <= maxInt
        }
    }
}

private fun isWithinMaxValue(text: String, maxValue: Double): Boolean {
    return try {
        text.toDouble() <= maxValue
    } catch (e: NumberFormatException) {
        false
    }
}
