package com.adealink.weparty.commonui.widget.floatview.view

import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.animation.DecelerateInterpolator
import android.view.animation.LinearInterpolator
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.animation.addListener

open class SwipeToTopConstraintLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {

    private var startY: Float = 0f
    private var lastY: Float = 0f
    private var initialTranslationY: Float = 0f
    private val moveThreshold = 5 // 滑动的最小距离，单位是像素
    private val updateThreshold = 1 // 更新的最小距离，单位是像素
    private var maxTranslationY = 500f // 最大的 translationY 范围
    private var minTranslationY = -500f // 最小的 translationY 范围
    private val hideThreshold = 50f // 向上滑动的距离阈值，超过此距离视图将滑出屏幕
    private var animator: ValueAnimator? = null
    private var isAnimating = false
    private var lastTranslationY: Float = 0f
    private var smoothFactor = 0.4f // 平滑因子，值越小越平滑
    private var isViewHidden = false // 标志视图是否被滑出
    private var viewHeight = 0 // 视图的高度
    private var hideMode = HideMode.MODE_AUTO
    private var onHideListener: ((mode: HideMode) -> Unit)? = null
    private var touchDispatchEventListener: ITouchDispatchEventListener? = null
    private var isClick = false // 标志是否是点击事件

    companion object{
        const val DEFAULT_DELAY_TIME = 5000L
    }

    fun setTouchDispatchEventListener(listener: ITouchDispatchEventListener) {
        this.touchDispatchEventListener = listener
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        viewHeight = measuredHeight
        maxTranslationY = measuredHeight.toFloat()
        minTranslationY = -maxTranslationY
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        //只分发单指的事件
        if (event.pointerCount == 1) {
            touchDispatchEventListener?.onTouchDispatchEvent(event)
        }

        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                startY = event.y
                lastY = startY
                initialTranslationY = translationY
                lastTranslationY = initialTranslationY
                isAnimating = false
                isClick = true // 初始认为是点击事件
                return true
            }

            MotionEvent.ACTION_MOVE -> {
                if (isAnimating) {
                    return true
                }

                val deltaY = event.y - lastY
                if (Math.abs(deltaY) > moveThreshold) {
                    isClick = false // 如果有滑动，则不是点击事件
                    // 使用平滑因子来平滑 deltaY
                    val smoothedDeltaY = deltaY * smoothFactor
                    val newTranslationY = lastTranslationY + smoothedDeltaY

                    // 限制 translationY 的范围，避免过大的变化
                    if (newTranslationY > maxTranslationY) {
                        translationY = maxTranslationY
                    } else if (newTranslationY < minTranslationY) {
                        translationY = minTranslationY
                    } else {
                        if (Math.abs(newTranslationY - translationY) > updateThreshold) {
                            translationY = newTranslationY
                        }
                    }

                    lastY = event.y
                    lastTranslationY = translationY
                }
                return true
            }

            MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                if (isAnimating) {
                    return true
                }
                if (isClick) {
                    // 如果是点击事件，触发跳转逻辑
                    performClick()
                } else {
                    // 计算向上滑动的距离
                    val totalSlideDistance = initialTranslationY - translationY

                    if (totalSlideDistance > hideThreshold) {
                        // 如果滑动距离超过阈值，滑出屏幕并隐藏视图
                        hideView(HideMode.MODE_MANUAL)
                    } else {
                        // 否则执行回弹动画
                        animator?.cancel()
                        animator = ValueAnimator.ofFloat(translationY, initialTranslationY).apply {
                            duration = 300
                            interpolator = DecelerateInterpolator() // 添加插值器来平滑动画
                            addUpdateListener {
                                translationY = it.animatedValue as Float
                            }
                            start()
                        }
                    }
                }
                isAnimating = true
                return true
            }
        }
        return super.onTouchEvent(event)
    }

    // 主动隐藏视图
    fun hideViewWithAnimation() {
        animator?.cancel()
        animator = ValueAnimator.ofFloat(translationY, -viewHeight.toFloat()).apply {
            duration = 200 // 设置动画时长为200毫秒
            interpolator = LinearInterpolator() // 添加线性插值器来平滑动画
            addUpdateListener {
                translationY = it.animatedValue as Float
            }
            addListener(onEnd = {
                hideView()
            })
            start()
        }
    }

    open fun hideView(mode: HideMode = HideMode.MODE_AUTO) {
        onHideListener?.invoke(mode)
        visibility = GONE // 动画结束后隐藏视图
        setHidden()
        this.hideMode = mode
    }

    // 重置 SwipeAnimateView 到初始位置
    fun resetToInitialPosition() {
        if (visibility == GONE) {
            visibility = VISIBLE
            animator?.cancel()
            animator = ValueAnimator.ofFloat(translationY, initialTranslationY).apply {
                duration = 300 // 动画时长为300毫秒
                interpolator = DecelerateInterpolator() // 添加插值器来平滑动画
                addUpdateListener {
                    translationY = it.animatedValue as Float
                }
                addListener(onEnd = {
                    isAnimating = false
                    setShown()
                })
                start()
            }
        }
    }

    // 直接重置 SwipeAnimateView 到初始位置
    fun resetToInitialPositionImmediately() {
        if (visibility == GONE) {
            visibility = VISIBLE
        }
        translationY = initialTranslationY
        isAnimating = false
        setShown()
    }

    private fun setHidden() {
        isViewHidden = true
    }

    private fun setShown() {
        this.hideMode = HideMode.MODE_AUTO
        isViewHidden = false
    }

    // 判断视图是否被滑出
    fun isViewHidden(): Boolean {
        return isViewHidden
    }

    fun hideMode(): HideMode {
        return hideMode
    }

    fun setOnHideListener(listener: (mode: HideMode) -> Unit) {
        this.onHideListener = listener
    }
}

interface ITouchDispatchEventListener {

    fun onTouchDispatchEvent(event: MotionEvent?) {}
}

enum class HideMode {
    MODE_MANUAL,//手动
    MODE_AUTO//自动
}








