package com.example.base.extensions

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.LinearGradient
import android.graphics.RectF
import android.graphics.Shader
import android.graphics.drawable.ShapeDrawable
import android.view.View
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.inputmethod.InputMethodManager


/**
 * @date 2020-06-12 17:27
 * @desc TODO
 */
fun View.calcViewScreenLocation(): RectF {

    val location = IntArray(2)
    // 获取控件在屏幕中的位置，返回的数组分别为控件左顶点的 x、y 的值
    this.getLocationOnScreen(location)
    return RectF(
        location[0].toFloat(),
        location[1].toFloat(),
        location[0] + this.width.toFloat(),
        location[1] + this.height.toFloat()
    )

}

fun View.isInViewRect(x: Float, y: Float): Boolean {
    val rect = calcViewScreenLocation()
    return rect.contains(x, y)
}

fun View.closeKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(this.windowToken, InputMethodManager.HIDE_IMPLICIT_ONLY)
}

/**
 * 淡入淡出动画
 */
fun View.animCrossFade(isShow: Boolean, duration: Long = 600) {
    this.apply {
        alpha = if (isShow) 0f else 1f
        visibility = View.VISIBLE

        animate()
            .alpha(if (isShow) 1f else 0f)
            .setDuration(duration)
            .setListener(object : AnimatorListenerAdapter() {
                override fun onAnimationEnd(animation: Animator) {
                    if (!isShow) {
                        this@animCrossFade.visibility = View.GONE
                    }
                }
            })
    }
}

fun View.gone() {
    if (visibility != View.GONE) {
        visibility = View.GONE
    }
}

fun View.gone(gone: Boolean) {
    if (gone && visibility != View.GONE) {
        visibility = View.GONE
    } else if (!gone && visibility == View.GONE) {
        visibility = View.VISIBLE
    }
}

fun View.invisible() {
    if (visibility != View.INVISIBLE) {
        visibility = View.INVISIBLE
    }
}

fun View.visible() {
    if (visibility != View.VISIBLE) {
        visibility = View.VISIBLE
    }
}

fun View.visible(visible: Boolean) {
    if (visible && visibility != View.VISIBLE) {
        visibility = View.VISIBLE
    } else if (!visible && visibility == View.VISIBLE) {
        visibility = View.INVISIBLE
    }
}

fun View.screenshot(): Bitmap? {
    return runCatching {
        val screenshot = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val c = Canvas(screenshot)
        c.translate(-scrollX.toFloat(), -scrollY.toFloat())
        draw(c)
        screenshot
    }.getOrNull()
}

fun View.startBlinking() {
    val fadeIn = AlphaAnimation(0f, 1f).apply {
        duration = 500 // 设置每次淡入淡出的时间
        repeatMode = Animation.REVERSE // 反向重复模式
        repeatCount = Animation.INFINITE // 无限次重复
        interpolator = LinearInterpolator() // 使用线性插值器保证匀速变化
    }
    startAnimation(fadeIn)
}

fun View.isAniming() {

    clearAnimation() // 停止并移除当前所有动画
}

fun View.stopBlinking() {
    clearAnimation() // 停止并移除当前所有动画
}

fun View.changeGradientColors(startColor: Int, endColor: Int) {
    val currentShapeDrawable = background as? ShapeDrawable ?: return
    val paint = currentShapeDrawable.paint
    paint.shader = null
    val viewWidth = width.coerceAtLeast(1) // 防止宽度为0的情况
    val newShader = LinearGradient(
        0f,                               // 渐变开始的x坐标
        0f,                               // 渐变开始的y坐标
        viewWidth.toFloat(),               // 渐变结束的x坐标
        0f,                               // 假设为水平渐变，y坐标不变
        intArrayOf(startColor, endColor),  //  渐变颜色数组
        null,                     // 颜色分布位置，默认均匀分布
        Shader.TileMode.CLAMP             // 渐变边缘处理方式
    )
    paint.shader = newShader
    postInvalidate()
}
