package com.yidian.shenghuoquan.newscontent.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import android.widget.TextView
import com.yidian.shenghuoquan.newscontent.R
import com.yidian.utils.ToastUtil

/**
 * author : lidawei
 * date : 2021/6/1
 * description :
 */
class NumberCheckView @JvmOverloads constructor(
  context: Context,
  attributeSet: AttributeSet? = null,
  defStyle: Int = 0
) : LinearLayout(context, attributeSet, defStyle) {
  private var onNumberMatch: (() -> Unit)? = null
  private var onTextChange: ((Boolean, String) -> Unit)? = null
  private var tvStart: TextView
  private var etCheck: NumberWithBorderEditText
  private var tvEnd: TextView
  private var originalNumber = ""
  private var start = ""
  private var end = ""

  init {
    LayoutInflater.from(context).inflate(R.layout.layout_number_check, this, true)
    tvStart = findViewById(R.id.tv_start)
    tvEnd = findViewById(R.id.tv_end)
    etCheck = findViewById(R.id.et_check)

    etCheck.setOnTextChangeListener {
      if (originalNumber.isEmpty()) return@setOnTextChangeListener
      val numberC = "$start$it$end"
      if (numberC == originalNumber) {
        onNumberMatch?.invoke()
      }
      onTextChange?.invoke(numberC == originalNumber, numberC)
    }
  }


  fun setOriginalNumber(number: String) {
    originalNumber = number
    //简单校验
    if (originalNumber.length != 11) {
      ToastUtil.showToast(context, "手机号异常")
      return
    }
    start = originalNumber.substring(0, 3)
    end = originalNumber.substring(11 - 4)
    tvStart.text = start
    tvEnd.text = end
  }

  /**
   * 号码输入时监听
   */
  fun setOnTextChangListener(onTextChange: (/*输入结果是否正确*/Boolean, String) -> Unit) {
    this.onTextChange = onTextChange
  }

  /**
   * 号码完全匹配监听
   */
  fun setOnNumberMatchListener(onNumberMatch: () -> Unit) {
    this.onNumberMatch = onNumberMatch
  }

}
