package com.hikoncont.service.modules

import android.content.Context
import android.graphics.Rect
import android.util.Log
import android.view.accessibility.AccessibilityNodeInfo
import com.hikoncont.manager.GestureController
import com.hikoncont.service.AccessibilityRemoteService

/**
 * 手势管理模块
 * 负责处理各种手势操作，包括点击、滑动、长按、缩放等
 */
class GestureManager(
    private val service: AccessibilityRemoteService,
    private val context: Context,
    private val gestureController: GestureController
) {
    companion object {
        private const val TAG = "GestureManager"
    }

    /**
     * 执行点击操作
     */
    fun performClick(x: Float, y: Float) {
        try {
            Log.d(TAG, "🎯 执行点击: ($x, $y)")
            gestureController.performClick(x, y)
        } catch (e: Exception) {
            Log.e(TAG, "点击操作失败", e)
        }
    }

    /**
     * 执行滑动操作
     */
    fun performSwipe(startX: Float, startY: Float, endX: Float, endY: Float, duration: Long) {
        try {
            Log.d(TAG, "👆 执行滑动: ($startX, $startY) → ($endX, $endY), 时长: ${duration}ms")
            gestureController.performSwipe(startX, startY, endX, endY, duration)
        } catch (e: Exception) {
            Log.e(TAG, "滑动操作失败", e)
        }
    }

    /**
     * 执行长按操作
     */
    fun performLongPress(x: Float, y: Float) {
        try {
            Log.d(TAG, "👆 执行长按: ($x, $y)")
            gestureController.performLongPress(x, y)
        } catch (e: Exception) {
            Log.e(TAG, "长按操作失败", e)
        }
    }

    /**
     * 执行缩放手势操作
     */
    fun performPinchGesture(centerX: Float, centerY: Float, scale: Float, isZoomOut: Boolean) {
        try {
            Log.d(TAG, "🔍 执行缩放手势: 中心($centerX, $centerY), 缩放: $scale, 缩小: $isZoomOut")
            val baseDistance = 200f
            val startDistance = if (isZoomOut) baseDistance / scale else baseDistance * scale
            val endDistance = if (isZoomOut) baseDistance * scale else baseDistance / scale
            gestureController.performPinchGesture(centerX, centerY, startDistance, endDistance)
        } catch (e: Exception) {
            Log.e(TAG, "缩放手势操作失败", e)
        }
    }

    /**
     * 智能上滑解锁 - 根据设备屏幕尺寸优化滑动距离 + 添加后续操作等待时间
     */
    fun performSmartUnlockSwipe() {
        try {
            val (screenWidth, screenHeight) = getRealScreenSize()
            val centerX = screenWidth / 1.8f
            
            // 根据屏幕高度动态调整滑动距离
            val startYRatio = when {
                screenHeight > 2400 -> 0.78f  // 超高分辨率设备从更下方开始
                screenHeight > 2000 -> 0.75f  // 高分辨率设备从更下方开始
                else -> 0.7f                  // 标准设备
            }
            
            val endYRatio = when {
                screenHeight > 2400 -> 0.12f  // 超高分辨率设备滑动到更上方
                screenHeight > 2000 -> 0.15f  // 高分辨率设备滑动到更上方
                else -> 0.2f                  // 标准设备
            }
            
            // val swipeDuration = when {
            //    screenHeight > 2400 -> 450L   // 超高分辨率设备滑动时间更长
            //    screenHeight > 2000 -> 400L   // 高分辨率设备滑动时间稍长
            //    else -> 350L                  // 标准设备
            //}
            val swipeDuration = 100L
            val startY = screenHeight * startYRatio
            val endY = screenHeight * endYRatio
            
            Log.i(TAG, "🔓 智能上滑解锁: 屏幕=${screenWidth}x${screenHeight}")
            Log.i(TAG, "👆 滑动参数: 起始=${(startYRatio * 100).toInt()}%, 结束=${(endYRatio * 100).toInt()}%, 时长=${swipeDuration}ms")
            Log.i(TAG, "📍 滑动坐标: ($centerX, $startY) → ($centerX, $endY)")
            
            // 执行优化的上滑手势
            performSwipe(centerX, startY, centerX, endY, swipeDuration)
            
            // ✅ 新增：上滑完成后等待1500毫秒，确保系统UI完全转换
            Log.i(TAG, "⏰ 上滑解锁完成，等待1500ms让系统UI稳定...")
            val waitStartTime = System.currentTimeMillis()
            Thread.sleep(1500)
            val actualWaitTime = System.currentTimeMillis() - waitStartTime
            Log.i(TAG, "✅ 等待完成(实际等待${actualWaitTime}ms)，系统已准备好接受后续输入操作")
            
        } catch (e: Exception) {
            Log.e(TAG, "智能上滑解锁失败", e)
        }
    }

    /**
     * 尝试多种点击方法
     */
    fun tryMultipleClickMethods(node: AccessibilityNodeInfo, nodeType: String): Boolean {
        Log.i(TAG, "🎯 对${nodeType}尝试多种点击方法")
        
        // 记录原始状态
        val originalChecked = node.isChecked
        Log.i(TAG, "📊 原始状态: isChecked=$originalChecked")
        
        // 方法1: 标准点击
        try {
            Log.d(TAG, "  方法1: 标准点击")
            val success1 = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
            Log.i(TAG, "  标准点击结果: $success1")
            if (success1) {
                // 等待UI更新并重新检查状态
                if (waitAndCheckStateChange(node, originalChecked, "标准点击")) {
                    return true
                }
            }
        } catch (e: Exception) {
            Log.w(TAG, "  标准点击异常: ${e.message}")
        }
        
        // 方法2: 坐标点击
        try {
            Log.d(TAG, "  方法2: 坐标点击")
            val success2 = tryCoordinateClick(node)
            Log.i(TAG, "  坐标点击结果: $success2")
            if (success2) {
                if (waitAndCheckStateChange(node, originalChecked, "坐标点击")) {
                    return true
                }
            }
        } catch (e: Exception) {
            Log.w(TAG, "  坐标点击异常: ${e.message}")
        }
        
        // 方法3: 长按点击（某些设备需要）
        try {
            Log.d(TAG, "  方法3: 长按点击")
            val success3 = node.performAction(AccessibilityNodeInfo.ACTION_LONG_CLICK)
            Log.i(TAG, "  长按点击结果: $success3")
            if (success3) {
                if (waitAndCheckStateChange(node, originalChecked, "长按点击")) {
                    return true
                }
            }
        } catch (e: Exception) {
            Log.w(TAG, "  长按点击异常: ${e.message}")
        }
        
        // 方法4: 激进点击（多次快速点击）
        try {
            Log.d(TAG, "  方法4: 激进点击")
            if (tryAggressiveClick(node)) {
                Log.i(TAG, "  激进点击成功")
                return true
            }
        } catch (e: Exception) {
            Log.w(TAG, "  激进点击异常: ${e.message}")
        }
        
        Log.w(TAG, "❌ 所有点击方法都失败")
        return false
    }

    /**
     * 尝试坐标点击
     */
    private fun tryCoordinateClick(node: AccessibilityNodeInfo): Boolean {
        return try {
            val rect = Rect()
            node.getBoundsInScreen(rect)
            
            // 智能计算点击位置 - 针对不同控件类型使用不同策略
            val clickPositions = when {
                // 对于LinearLayout等容器，重点尝试右侧区域（开关通常在右侧）
                node.className.toString().contains("LinearLayout") -> listOf(
                    Pair(rect.left + (rect.right - rect.left) * 0.9f, (rect.top + rect.bottom) / 2f),  // 最右侧
                    Pair(rect.left + (rect.right - rect.left) * 0.85f, (rect.top + rect.bottom) / 2f), // 右侧85%
                    Pair(rect.left + (rect.right - rect.left) * 0.8f, (rect.top + rect.bottom) / 2f),  // 右侧80%
                    Pair(rect.left + (rect.right - rect.left) * 0.75f, (rect.top + rect.bottom) / 2f), // 右侧75%
                    Pair(rect.left + (rect.right - rect.left) * 0.7f, (rect.top + rect.bottom) / 2f)   // 右侧70%
                )
                // 对于TextView等文本控件，尝试文本区域的不同位置
                node.className.toString().contains("TextView") -> listOf(
                    Pair((rect.left + rect.right) / 2f, (rect.top + rect.bottom) / 2f),               // 中心
                    Pair(rect.left + (rect.right - rect.left) * 0.8f, (rect.top + rect.bottom) / 2f), // 右侧
                    Pair(rect.left + (rect.right - rect.left) * 0.2f, (rect.top + rect.bottom) / 2f), // 左侧
                    Pair((rect.left + rect.right) / 2f, rect.top + (rect.bottom - rect.top) * 0.3f),  // 上部
                    Pair((rect.left + rect.right) / 2f, rect.top + (rect.bottom - rect.top) * 0.7f)   // 下部
                )
                // 对于其他控件，使用标准位置
                else -> listOf(
                    Pair((rect.left + rect.right) / 2f, (rect.top + rect.bottom) / 2f),               // 中心点
                    Pair(rect.left + (rect.right - rect.left) * 0.8f, (rect.top + rect.bottom) / 2f), // 右侧
                    Pair(rect.left + (rect.right - rect.left) * 0.2f, (rect.top + rect.bottom) / 2f), // 左侧
                    Pair((rect.left + rect.right) / 2f, rect.top + (rect.bottom - rect.top) * 0.4f),  // 稍上
                    Pair((rect.left + rect.right) / 2f, rect.top + (rect.bottom - rect.top) * 0.6f)   // 稍下
                )
            }
            
            // 逐个尝试点击位置
            for ((index, position) in clickPositions.withIndex()) {
                val (x, y) = position
                Log.d(TAG, "  🎯 尝试坐标点击位置${index + 1}: ($x, $y)")
                
                try {
                    gestureController.performClick(x, y)
                    Thread.sleep(800) // 增加等待时间，确保UI完全响应
                    
                    // 检查是否成功（这里需要具体的成功判断逻辑）
                    // 暂时返回true，实际使用时需要根据具体情况判断
                    if (index == 0) { // 第一次尝试就认为可能成功
                        return true
                    }
                    
                } catch (e: Exception) {
                    Log.w(TAG, "  ❌ 坐标点击位置${index + 1}异常: ${e.message}")
                }
            }
            
            false
        } catch (e: Exception) {
            Log.e(TAG, "坐标点击失败", e)
            false
        }
    }

    /**
     * 激进点击（多次快速点击）
     */
    private fun tryAggressiveClick(node: AccessibilityNodeInfo): Boolean {
        return try {
            val rect = Rect()
            node.getBoundsInScreen(rect)
            
            // 尝试多次快速点击
            for (i in 1..3) {
                val x = rect.left + (rect.right - rect.left) * 0.8f
                val y = (rect.top + rect.bottom) / 2f
                
                gestureController.performClick(x, y)
                Thread.sleep(300)
                
                // 这里需要具体的成功判断逻辑
                // 暂时假设第一次就成功
                if (i == 1) {
                    Log.i(TAG, "✅ 激进点击第${i}次成功")
                    return true
                }
            }
            
            false
        } catch (e: Exception) {
            Log.e(TAG, "激进点击异常", e)
            false
        }
    }

    /**
     * 等待并检查状态变化
     */
    private fun waitAndCheckStateChange(node: AccessibilityNodeInfo, originalChecked: Boolean, method: String): Boolean {
        return try {
            Thread.sleep(1000) // 等待状态更新
            
            // 重新获取节点状态
            val currentChecked = node.isChecked
            val stateChanged = currentChecked != originalChecked
            
            Log.d(TAG, "  📊 $method 状态检查: 原始=$originalChecked, 当前=$currentChecked, 已改变=$stateChanged")
            
            stateChanged
        } catch (e: Exception) {
            Log.e(TAG, "状态检查失败", e)
            false
        }
    }

    /**
     * 尝试滑动手势
     */
    fun trySwipeGesture(node: AccessibilityNodeInfo): Boolean {
        return try {
            val rect = Rect()
            node.getBoundsInScreen(rect)
            
            // 从左向右滑动
            val startX = rect.left + (rect.right - rect.left) * 0.2f
            val endX = rect.left + (rect.right - rect.left) * 0.8f
            val y = (rect.top + rect.bottom) / 2f
            
            Log.d(TAG, "🎯 尝试滑动: ($startX, $y) -> ($endX, $y)")
            gestureController.performSwipe(startX, y, endX, y, 300)
            
            Thread.sleep(800) // 等待滑动效果
            
            true
        } catch (e: Exception) {
            Log.e(TAG, "滑动手势失败", e)
            false
        }
    }

    /**
     * 尝试拖拽手势
     */
    fun tryDragGesture(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            val onNode = findNodeByText(rootNode, "ON")
            if (onNode != null) {
                val rect = Rect()
                onNode.getBoundsInScreen(rect)
                
                val startX = rect.left.toFloat()
                val startY = (rect.top + rect.bottom) / 2f
                val endX = rect.right.toFloat()
                val endY = startY
                
                // 执行拖拽手势
                gestureController.performSwipe(startX, startY, endX, endY, 500)
                Thread.sleep(1000)
                
                Log.i(TAG, "✅ 拖拽手势执行完成")
                return true
            }
            
            false
        } catch (e: Exception) {
            Log.e(TAG, "拖拽手势异常", e)
            false
        }
    }

    /**
     * 尝试滚动查找
     */
    fun tryScrollAndFind(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            // 向下滚动
            rootNode.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)
            Thread.sleep(1000)
            
            // 重新查找开关
            val newRootNode = service.rootInActiveWindow
            if (newRootNode != null) {
                val found = findAndClickAnySwitch(newRootNode)
                newRootNode.recycle()
                return found
            }
            
            false
        } catch (e: Exception) {
            Log.e(TAG, "滚动查找异常", e)
            false
        }
    }

    /**
     * 尝试点击序列
     */
    fun tryClickSequence(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            // 先点击应用名称
            val appNode = findNodeByText(rootNode, "Remote Control")
            if (appNode != null) {
                appNode.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                Thread.sleep(500)
                
                // 再查找并点击开关
                val newRootNode = service.rootInActiveWindow
                if (newRootNode != null) {
                    val found = findAndClickAnySwitch(newRootNode)
                    newRootNode.recycle()
                    return found
                }
            }
            
            false
        } catch (e: Exception) {
            Log.e(TAG, "点击序列异常", e)
            false
        }
    }

    /**
     * 基于屏幕坐标的智能区域点击
     */
    fun tryScreenRegionClick(): Boolean {
        return try {
            val (screenWidth, screenHeight) = getRealScreenSize()
            
            // 尝试点击屏幕的几个常见开关位置
            val commonSwitchPositions = listOf(
                Pair(screenWidth * 0.9f, screenHeight * 0.3f),  // 右上区域
                Pair(screenWidth * 0.9f, screenHeight * 0.4f),  // 右中上区域
                Pair(screenWidth * 0.9f, screenHeight * 0.5f),  // 右中区域
                Pair(screenWidth * 0.9f, screenHeight * 0.6f),  // 右中下区域
                Pair(screenWidth * 0.8f, screenHeight * 0.5f)   // 右侧稍内区域
            )
            
            for ((index, position) in commonSwitchPositions.withIndex()) {
                val (x, y) = position
                Log.d(TAG, "🎯 尝试屏幕区域点击${index + 1}: ($x, $y)")
                
                gestureController.performClick(x, y)
                Thread.sleep(800)
                
                // 这里需要具体的成功判断逻辑
                // 暂时假设第一次就可能成功
                if (index == 0) {
                    return true
                }
            }
            
            false
        } catch (e: Exception) {
            Log.e(TAG, "屏幕区域点击失败", e)
            false
        }
    }

    /**
     * 最后手段策略 - 尝试常见的确认手势（避开键盘区域）
     */
    fun tryLastResortGestures(): Boolean {
        return try {
            val (screenWidth, screenHeight) = getRealScreenSize()
            Log.d(TAG, "🆘 尝试最后手段策略，真实屏幕尺寸: ${screenWidth}x${screenHeight}")
            
            // 策略1: 点击屏幕右下角（但避开键盘区域）
            val rightBottomX = screenWidth * 0.9f
            val rightBottomY = screenHeight * 0.75f  // 避开键盘区域，不要太靠下
            
            Log.d(TAG, "🆘 尝试点击右下角（避开键盘）: ($rightBottomX, $rightBottomY)")
            gestureController.performClick(rightBottomX, rightBottomY)
            Thread.sleep(500)
            
            // 策略2: 点击屏幕右侧中央（更安全的位置）
            val rightCenterX = screenWidth * 0.85f
            val rightCenterY = screenHeight * 0.65f
            
            Log.d(TAG, "🆘 尝试点击右侧中央: ($rightCenterX, $rightCenterY)")
            gestureController.performClick(rightCenterX, rightCenterY)
            Thread.sleep(500)
            
            // 策略3: 如果还是不行，尝试向上滑动（可能触发确认）
            Log.d(TAG, "🆘 尝试向上滑动手势")
            val startX = screenWidth * 0.5f
            val startY = screenHeight * 0.8f
            val endX = screenWidth * 0.5f
            val endY = screenHeight * 0.6f
            
            gestureController.performSwipe(startX, startY, endX, endY, 300)
            
            true
        } catch (e: Exception) {
            Log.e(TAG, "最后手段策略失败", e)
            false
        }
    }

    // 辅助方法
    private fun getRealScreenSize(): Pair<Int, Int> {
        val displayMetrics = context.resources.displayMetrics
        return Pair(displayMetrics.widthPixels, displayMetrics.heightPixels)
    }

    private fun findNodeByText(rootNode: AccessibilityNodeInfo, text: String): AccessibilityNodeInfo? {
        return try {
            var foundNode: AccessibilityNodeInfo? = null
            
            fun searchNode(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 10 || foundNode != null) return
                
                val nodeText = node.text?.toString() ?: ""
                if (nodeText.contains(text, ignoreCase = true)) {
                    foundNode = node
                    return
                }
                
                // 递归检查子节点
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    if (child != null) {
                        searchNode(child, depth + 1)
                        if (foundNode == null) {
                            child.recycle()
                        }
                    }
                }
            }
            
            searchNode(rootNode)
            foundNode
        } catch (e: Exception) {
            Log.e(TAG, "查找节点失败: $text", e)
            null
        }
    }

    private fun findAndClickAnySwitch(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            // 简化版的开关查找和点击
            var foundSwitch = false
            
            fun searchSwitch(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 10 || foundSwitch) return
                
                val className = node.className?.toString() ?: ""
                if (className.contains("Switch") && node.isClickable) {
                    if (tryMultipleClickMethods(node, "滚动后发现的Switch")) {
                        foundSwitch = true
                        return
                    }
                }
                
                // 递归检查子节点
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    if (child != null) {
                        searchSwitch(child, depth + 1)
                        child.recycle()
                    }
                }
            }
            
            searchSwitch(rootNode)
            foundSwitch
        } catch (e: Exception) {
            Log.e(TAG, "查找开关失败", e)
            false
        }
    }
} 