package com.xty.common.weight

import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.widget.EditText


/**
 * Description: 小数位数限定
 */
class DecimalInputTextWatcher(editText: EditText?, totalDigits: Int, decimalDigits: Int) :
    TextWatcher {
    /**
     * 需要设置该 DecimalInputTextWatcher 的 EditText
     */
    private var mEditText: EditText? = null
    private val decimalDigits // 小数的位数
            : Int
    private val totalDigits //最大长度
            : Int

    override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
    override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
    override fun afterTextChanged(editable: Editable) {
        try {
            var s = editable.toString()
            mEditText!!.removeTextChangedListener(this)
            //限制最大长度
            mEditText!!.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(totalDigits))
            if (s.contains(Period)) {
                //超过小数位限定位数,只保留限定小数位数
                if (s.length - 1 - s.indexOf(Period) > decimalDigits) {
                    s = s.substring(
                        0,
                        s.indexOf(Period) + decimalDigits + 1
                    )
                    editable.replace(0, editable.length, s.trim { it <= ' ' })
                }
            }
            //如果首位输入"."自动补0
            if (s.trim { it <= ' ' } == Period) {
                s = Zero + s
                editable.replace(0, editable.length, s.trim { it <= ' ' })
            }
            //首位输入0时,不再继续输入
            if (s.startsWith(Zero)
                && s.trim { it <= ' ' }.length > 1
            ) {
                if (s.substring(1, 2) != Period) {
                    editable.replace(0, editable.length, Zero)
                }
            }
            mEditText!!.addTextChangedListener(this)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    companion object {
        private const val Period = "."
        private const val Zero = "0"

        /**
         * 默认  小数的位数   2 位
         */
        private const val DEFAULT_DECIMAL_DIGITS = 2
    }

    /**
     * @param editText      editText
     * @param totalDigits   最大长度
     * @param decimalDigits 小数的位数
     */
    init {
        if (editText == null) {
            throw RuntimeException("editText can not be null")
        }
        mEditText = editText
        if (totalDigits <= 0) throw RuntimeException("totalDigits must > 0")
        if (decimalDigits <= 0) throw RuntimeException("decimalDigits must > 0")
        this.totalDigits = totalDigits
        this.decimalDigits = decimalDigits
    }
}