package com.audio.record.screen.test.tool

import android.annotation.SuppressLint
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager

object DraggableViewHelper {


    /**
     * view大小自适应，在全屏拖拽，更新在windows上的位置
     * @param snapToEdge 是否吸边
     */
    @SuppressLint("ClickableViewAccessibility")
    fun attachToWindow(
        view: View,
        layoutParams: WindowManager.LayoutParams,
        windowManager: WindowManager,
        snapToEdge: Boolean = true,
        onClick: (() -> Unit)? = null
    ) {
        var dX = 0
        var dY = 0
        var downTime = 0L
        var isDragging = false

        val clickThreshold = 200   // 毫秒，判断点击
        val moveThreshold = 10     // 像素，判断是否移动

        val screenWidth = Common.getScreenWH(view.context).first
        val screenHeight = Common.getScreenWH(view.context).second


        view.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    dX = (event.rawX - layoutParams.x).toInt()
                    dY = (event.rawY - layoutParams.y).toInt()

                    downTime = System.currentTimeMillis()
                    isDragging = false
                    true
                }

                MotionEvent.ACTION_MOVE -> {

                    val newX = (event.rawX - dX).toInt()
                    val newY = (event.rawY - dY).toInt()

                    // 判断是否是有效拖动
                    if (kotlin.math.abs(newX - layoutParams.x) > moveThreshold ||
                        kotlin.math.abs(newY - layoutParams.y) > moveThreshold
                    ) {
                        isDragging = true
                    }

                    // 计算新的位置
                    layoutParams.x = (event.rawX - dX).toInt().coerceIn(0, screenWidth - view.width)
                    layoutParams.y =
                        (event.rawY - dY).toInt().coerceIn(0, screenHeight - view.height)

                    // 更新 window
                    windowManager.updateViewLayout(view, layoutParams)
                    true
                }

                MotionEvent.ACTION_UP -> {

                    if (!isDragging && System.currentTimeMillis() - downTime < clickThreshold) {
                        if (onClick != null) {
                            onClick.invoke()
                        }
                    } else if (snapToEdge) {
                        val middle = screenWidth / 2
                        layoutParams.x = if (layoutParams.x + view.width / 2 <= middle) {
                            0
                        } else {
                            screenWidth - view.width
                        }
                        windowManager.updateViewLayout(view, layoutParams)
                    }
                    true
                }

                else -> false
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    fun attach(view: View, snapToEdge: Boolean = true) {
        var dX = 0f
        var dY = 0f

        val displayMetrics = view.context.resources.displayMetrics
        val screenWidth = displayMetrics.widthPixels
        val screenHeight = displayMetrics.heightPixels
        Common.showLog("--------screenWidth=$screenWidth  screenHeight=${screenHeight}")

        view.setOnTouchListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    dX = event.rawX - v.x
                    dY = event.rawY - v.y
                    true
                }

                MotionEvent.ACTION_MOVE -> {
                    var newX = event.rawX - dX
                    var newY = event.rawY - dY

                    // 限制不出屏幕
                    newX = newX.coerceIn(0f, (screenWidth - v.width).toFloat())
                    newY = newY.coerceIn(0f, (screenHeight - v.height).toFloat())

                    v.x = newX
                    v.y = newY
                    true
                }

                MotionEvent.ACTION_UP -> {
                    if (snapToEdge) {
                        // 吸边：判断中线位置
                        val middle = screenWidth / 2
                        val targetX = if (v.x + v.width / 2 <= middle) {
                            0f // 左吸边
                        } else {
                            (screenWidth - v.width).toFloat() // 右吸边
                        }

                        // 动画吸附
                        v.animate()
                            .x(targetX)
                            .setDuration(200)
                            .start()
                    }
                    true
                }

                else -> false
            }
        }
    }


}
