package com.example.base.extensions

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import java.math.RoundingMode
import java.text.DecimalFormat


/**
 * 显示输入法
 */
fun EditText.showKeyboard() {
    this.requestFocus()
    val imm = this.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.SHOW_FORCED)
}

fun EditText.hideKeyboard() {
    this.requestFocus()
    val imm = this.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(windowToken, InputMethodManager.SHOW_FORCED)
}

/**
 * 限制只能输入两位小数
 */
fun EditText.setTwoDecimalLimit() {

    val df = DecimalFormat()
    df.applyPattern("#0.00")
    df.roundingMode = RoundingMode.FLOOR

    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            val length = s?.split(".")?.last()?.length ?: 0
            if (length > 2 && s?.contains(".") == true) {
                val t = df.format(s.toString().toDouble())
                this@setTwoDecimalLimit.text = Editable.Factory.getInstance().newEditable(t)
                this@setTwoDecimalLimit.setSelection(s.length - 1)
            }
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

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

}

/**
 * 把输入手机号格式化有空格的
 */
fun EditText.setPhoneInput() {
    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {

        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(
            charSequence: CharSequence?,
            start: Int,
            before: Int,
            count: Int
        ) {
            if (charSequence == null || charSequence.trim().isEmpty()) return
            val stringBuilder = StringBuilder()
            for (i in charSequence.indices) {
                if (i != 3 && i != 8 && charSequence[i] == ' ') {
                    continue
                } else {
                    stringBuilder.append(charSequence[i])
                    if ((stringBuilder.length == 4 || stringBuilder.length == 9)
                        && stringBuilder[stringBuilder.length - 1] != ' '
                    ) {
                        stringBuilder.insert(stringBuilder.length - 1, ' ')
                    }
                }
            }
            if (stringBuilder.toString() != charSequence.toString()) {
                var index = start + 1
                if (stringBuilder[start] == ' ') {
                    if (before == 0) {
                        index++
                    } else {
                        index--
                    }
                } else {
                    if (before == 1) {
                        index--
                    }
                }
                this@setPhoneInput.setText(stringBuilder.toString())
                this@setPhoneInput.setSelection(index)
            }
        }
    })
}
