package com.yidian.bcommon.extensions

import android.os.SystemClock
import android.view.View
import android.widget.TextView
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import java.util.*

/**
 * 按钮点击防抖
 */
fun View?.clickAntiShake(intervalMillis: Long = 300, listener: (View) -> Unit) {
  // 最近一次点击的时间
  var lastClickTime: Long = 0
  this?.setOnClickListener {
    // 自启动以来的毫秒数，包括在睡眠中花费的时间
    val currentTime = SystemClock.elapsedRealtime()
    if (currentTime - lastClickTime >= intervalMillis) {
      listener.invoke(it)
      lastClickTime = currentTime
    }
  }
}


/**
 * 指定时间内连续点击触发相应操作
 */
fun View?.continuousClick(minimumClicks: Int = 6, listener: (View) -> Unit) {
  var time: Long = 0 //上次点击时间
  var count = 1 //当前点击次数
  this?.setOnClickListener {
    val timeNew = Date().time
    if ((timeNew - time) < 2000) { //连续点击间隔
      count += 1
    } else {
      count = 1
    }
    time = timeNew
    if (count >= minimumClicks) {  //点击次数
      listener.invoke(it) //触发后五连点之后需要做的事情
    }
  }

}

fun View.hide() {
  this.visibility = View.GONE
}

fun View.show() {
  this.visibility = View.VISIBLE
}

fun View.toggleVisibility() {
  if (this.visibility == View.GONE) {
    this.show()
  } else {
    this.hide()
  }
}

fun View.toggleVisibility(show: Boolean) {
  if (show) {
    this.show()
  } else {
    this.hide()
  }
}

fun View.setBgColor(@ColorRes colorId: Int) {
  val colorInt = ContextCompat.getColor(context, colorId)
  setBackgroundColor(colorInt)
}

fun TextView.setFgColor(@ColorRes colorId: Int) {
  val colorInt = ContextCompat.getColor(context, colorId)
  setTextColor(colorInt)
}

fun TextView.clearDrawable() {
  setCompoundDrawables(null, null, null, null)
}
