package com.gh.gamecenter.common.view

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewConfiguration
import androidx.recyclerview.widget.RecyclerView
import kotlin.math.abs

/**
 * 如非特殊情况请勿使用,会强行改变RecyclerView的拦截事件,可能会出现意料之外的问题
 */
class TouchSlopRecyclerView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
    RecyclerView(context, attrs) {

    private var mPrevX = 0f

    // 触控角度,用来控制触发左右滑动的敏感度
    var touchSlop = ViewConfiguration.get(context).scaledTouchSlop

    // 默认关闭,否则会误杀上下滑动事件
    var touchSlopEnabled = false

    override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> mPrevX = event.x
            MotionEvent.ACTION_MOVE -> {
                val eventX = event.x
                val xDiff = abs(eventX - mPrevX)
                if (touchSlopEnabled && xDiff > touchSlop) {
                    return false
                }
            }
        }
        return super.onInterceptTouchEvent(event)
    }
}