package com.yidian.shenghuoquan.newscontent.utils

import android.text.InputFilter
import java.util.regex.Pattern


/**
 * author: yinjiacheng
 * date: 6/15/21 1:59 AM
 * description: 输入过滤
 */
class InputFilterUtil {

  companion object {
    /**
     * 真实姓名过滤
     * 汉字 + ·
     */
    fun getRealNameFilter(): InputFilter {
      return InputFilter { source, _, _, _, _, _ ->
        val pattern = Pattern.compile("[\\u4E00-\\u9FFF|·]+")
        val matcher = pattern.matcher(source.toString())
        if (!matcher.matches()) return@InputFilter ""
        return@InputFilter null
      }
    }

    /**
     * 身份证号过滤
     * 数字 + X
     */
    fun getIDCardNumberFilter(): InputFilter {
      return InputFilter { source, _, _, _, _, _ ->
        val pattern = Pattern.compile("[0-9|X]+")
        val matcher = pattern.matcher(source.toString())
        if (!matcher.matches()) return@InputFilter ""
        return@InputFilter null
      }
    }

    /**
     * 手机号过滤
     * 数字
     */
    fun getPhoneNumberFilter(): InputFilter {
      return InputFilter { source, _, _, _, _, _ ->
        val pattern = Pattern.compile("[0-9]+")
        val matcher = pattern.matcher(source.toString())
        if (!matcher.matches()) return@InputFilter ""
        return@InputFilter null
      }
    }

    /**
     * 公司注册名过滤
     * 汉字
     */
    fun getRegistrationNameFilter(): InputFilter {
      return InputFilter { source, _, _, _, _, _ ->
        val pattern = Pattern.compile("[\\u4E00-\\u9FFF]+")
        val matcher = pattern.matcher(source.toString())
        if (!matcher.matches()) return@InputFilter ""
        return@InputFilter null
      }
    }

    /**
     * 统一社会信用代码过滤
     * 数字 + 大小写字母
     */
    fun getRegistrationCodeFilter(): InputFilter {
      return InputFilter { source, _, _, _, _, _ ->
        val pattern = Pattern.compile("[0-9A-Za-z]+")
        val matcher = pattern.matcher(source.toString())
        if (!matcher.matches()) return@InputFilter ""
        return@InputFilter null
      }
    }

    /**
     * 带回调的输入长度过滤
     */
    fun getLengthFilter(maxLength: Int, callback: OnLengthFilterCallback?): InputFilter {
      return InputFilter { _, _, end, _, dstart, _ ->
        if (dstart + end >= maxLength + 1) {
          callback?.onLengthOverrun(maxLength)
          return@InputFilter ""
        }
        return@InputFilter null
      }
    }
  }

  interface OnLengthFilterCallback {
    /**
     * 长度超限
     * @param maxLength 最大长度
     */
    fun onLengthOverrun(maxLength: Int)
  }
}
