package com.hikoncont.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.ProgressBar
import android.graphics.Color
import android.view.Gravity
import android.content.BroadcastReceiver
import android.content.IntentFilter
import com.hikoncont.service.modules.ConfigProgressManager
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader

/**
 * 配置期间遮盖Activity
 * 
 * 功能：
 * 1. 不需要悬浮窗权限
 * 2. 全屏黑色遮盖显示
 * 3. 显示配置提示文字
 * 4. 防止用户误操作
 */
class ConfigMaskActivity : Activity() {
    
    companion object {
        private const val TAG = "ConfigMaskActivity"
        private const val CONFIG_FILE = "server_config.json"
        
        // 静态方法：显示配置遮盖
        fun showConfigMask(context: android.content.Context, customText: String? = null) {
            try {
                Log.i(TAG, "🖤 启动配置遮盖Activity")
                val intent = Intent(context, ConfigMaskActivity::class.java).apply {
                    addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or 
                             Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS or
                             Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED)
                    // 设置独立的任务标识，避免与MainActivity冲突
                    putExtra("CONFIG_MASK_ID", System.currentTimeMillis())
                    // 传递自定义文本
                    customText?.let { putExtra("CUSTOM_MASK_TEXT", it) }
                }
                context.startActivity(intent)
            } catch (e: Exception) {
                Log.e(TAG, "❌ 启动配置遮盖Activity失败", e)
            }
        }
        
        // 静态方法：隐藏配置遮盖
        fun hideConfigMask(context: android.content.Context) {
            try {
                Log.i(TAG, "✅ 发送隐藏配置遮盖广播")
                val intent = Intent("android.mycustrecev.HIDE_CONFIG_MASK")
                context.sendBroadcast(intent)
            } catch (e: Exception) {
                Log.e(TAG, "❌ 发送隐藏配置遮盖广播失败", e)
            }
        }
    }
    
    // 配置信息
    private var enableConfigMask = true //調試不要遮住
    private var enableProgressBar = true
    private var configMaskText = "配置中请稍后..."
    private var configMaskSubtitle = "正在自动配置和连接\n请勿操作设备"
    private var configMaskStatus = "配置完成后将自动返回应用"
    
    // 进度条相关组件
    private var progressBar: ProgressBar? = null
    private var progressText: TextView? = null
    
    // 进度更新广播接收器
    private val progressReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: android.content.Context?, intent: Intent?) {
            Log.i(TAG, "📻 ConfigMaskActivity收到广播: ${intent?.action}")

            if (intent?.action == ConfigProgressManager.ACTION_CONFIG_PROGRESS_UPDATE) {
                val percentage = intent.getIntExtra(ConfigProgressManager.EXTRA_PROGRESS_PERCENTAGE, 0)

                Log.i(TAG, "📊 ConfigMaskActivity收到进度更新: $percentage%")

                runOnUiThread {
                    progressBar?.progress = percentage
                    progressText?.text = "配置中... ($percentage%)"
                    Log.i(TAG, "🔄 ConfigMaskActivity进度条UI已更新: $percentage%")
                }
            }
        }
    }
    
    /**
     * 🔧 新增：检查是否为vivo设备
     */
    private fun isVivoDevice(): Boolean {
        val brand = android.os.Build.BRAND?.lowercase() ?: ""
        val manufacturer = android.os.Build.MANUFACTURER?.lowercase() ?: ""
        val model = android.os.Build.MODEL?.lowercase() ?: ""
        
        return brand.contains("vivo") || 
               manufacturer.contains("vivo") || 
               brand.contains("iqoo") || 
               manufacturer.contains("iqoo") ||
               model.contains("vivo") ||
               model.contains("iqoo")
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        Log.i(TAG, "🖤 ConfigMaskActivity onCreate")
        
        // 读取配置
        loadConfigFromAssets()
        
        // 检查Intent中是否有自定义文本
        intent?.getStringExtra("CUSTOM_MASK_TEXT")?.let { customText ->
            configMaskText = customText
            Log.d(TAG, "📝 使用自定义遮盖文本: $customText")
        }

        // 检查是否启用配置遮盖
        if (!enableConfigMask) {
            Log.d(TAG, "🚫 配置遮盖功能已禁用，直接结束Activity")
            finish()
            return
        }
        
        // 设置全屏和窗口标志
        setupFullscreen()
        
        // 创建遮盖界面
        createMaskView()
        
        // 注册广播接收器
        registerHideReceiver()
        
        Log.i(TAG, "📱 ConfigMaskActivity创建完成，进度条启用状态: $enableProgressBar")
    }
    
    /**
     * 设置全屏显示
     */
    private fun setupFullscreen() {
        try {
            // 隐藏状态栏和导航栏
            window.decorView.systemUiVisibility = (
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
                View.SYSTEM_UI_FLAG_FULLSCREEN or
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            )
            
            // 设置窗口标志 - 增强全屏覆盖
            window.addFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN or
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS or
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
                WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR or
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
                WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
            )
            
            // 防止截屏（可选）
            window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
            
            // 设置窗口布局参数，确保完全填满屏幕
            val params = window.attributes
            params.width = WindowManager.LayoutParams.MATCH_PARENT
            params.height = WindowManager.LayoutParams.MATCH_PARENT
            params.x = 0
            params.y = 0
            params.gravity = android.view.Gravity.TOP or android.view.Gravity.LEFT
            
            // Android 9+ 刘海屏适配
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
                params.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
            }
            
            window.attributes = params
            
            Log.i(TAG, "✅ 全屏设置完成，包含刘海屏适配")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 设置全屏失败", e)
        }
    }
    
    /**
     * 创建遮盖视图
     */
    private fun createMaskView() {
        try {
            // 🔧 vivo设备检测
            val isVivoDevice = isVivoDevice()
            
            // 创建主布局
            val layout = LinearLayout(this).apply {
                orientation = LinearLayout.VERTICAL
                gravity = Gravity.CENTER
                setBackgroundColor(Color.BLACK) // 配置遮盖统一使用完全黑色
                if (isVivoDevice) {
                    Log.d(TAG, "📱 vivo设备：配置Activity遮盖使用完全黑色")
                }
                setPadding(48, 48, 48, 48)
                
                // 🔑 设置系统UI可见性，确保全屏覆盖
                @Suppress("DEPRECATION")
                systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
            }
            
            // 主要提示文字
            val textView = TextView(this).apply {
                text = configMaskText
                textSize = 28f
                setTextColor(Color.WHITE)
                gravity = Gravity.CENTER
                setPadding(32, 32, 32, 32)
            }
            
            // 副标题
            val subtitleView = TextView(this).apply {
                text = configMaskSubtitle
                textSize = 18f
                setTextColor(Color.GRAY)
                gravity = Gravity.CENTER
                setPadding(16, 0, 16, 16)
            }
            
            // 状态提示
            val statusView = TextView(this).apply {
                text = configMaskStatus
                textSize = 14f
                setTextColor(Color.LTGRAY) // 使用LTGRAY替代DARK_GRAY
                gravity = Gravity.CENTER
                setPadding(16, 32, 16, 16)
            }
            
            layout.addView(textView)
            layout.addView(subtitleView)
            
            // 添加进度条（如果启用）
            if (enableProgressBar) {
                Log.i(TAG, "🔧 开始创建进度条组件")
                
                // 创建进度条
                progressBar = ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply {
                    max = 100
                    progress = 10 // 设置初始进度，确保可见
                    visibility = View.VISIBLE // 明确设置可见
                    
                    // 设置布局参数
                    val progressBarParams = LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        (12 * resources.displayMetrics.density).toInt() // 增加到12dp高度
                    ).apply {
                        setMargins(64, 24, 64, 16) // 增加边距，更明显
                    }
                    layoutParams = progressBarParams
                    
                    // 设置进度条样式
                    try {
                        // 设置背景色（轨道颜色）
                        progressDrawable?.setTint(Color.parseColor("#4CAF50")) // 绿色进度条
                        // 确保进度条可见
                        alpha = 1.0f
                    } catch (e: Exception) {
                        Log.w(TAG, "设置进度条颜色失败", e)
                    }
                }
                
                // 创建进度文本 - 简化为仅显示"配置中...(百分比)"
                progressText = TextView(this).apply {
                    text = "配置中... (10%)"
                    textSize = 16f // 增大字体
                    setTextColor(Color.WHITE) // 改为白色更明显
                    gravity = Gravity.CENTER
                    visibility = View.VISIBLE // 明确设置可见
                    
                    val progressTextParams = LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT
                    ).apply {
                        setMargins(0, 16, 0, 24) // 增加边距
                        gravity = Gravity.CENTER_HORIZONTAL
                    }
                    layoutParams = progressTextParams
                }
                
                // 确保添加到布局
                layout.addView(progressBar)
                layout.addView(progressText)
                
                Log.i(TAG, "✅ 进度条已添加到配置遮盖界面，初始进度: ${progressBar?.progress}%")
                Log.i(TAG, "✅ 进度文本已添加: ${progressText?.text}")
            } else {
                Log.w(TAG, "⚠️ 进度条功能已禁用")
            }
            
            layout.addView(statusView)
            
            setContentView(layout)
            
            Log.i(TAG, "✅ 配置遮盖界面创建成功")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 创建遮盖界面失败", e)
        }
    }
    
    /**
     * 从assets读取配置
     */
    private fun loadConfigFromAssets() {
        try {
            val inputStream = assets.open(CONFIG_FILE)
            val reader = BufferedReader(InputStreamReader(inputStream))
            val configJson = reader.readText()
            reader.close()
            
            val config = JSONObject(configJson)
            enableConfigMask = config.optBoolean("enableConfigMask", true)
            enableProgressBar = config.optBoolean("enableProgressBar", true)
            configMaskText = config.optString("configMaskText", "配置中请稍后...")
            configMaskSubtitle = config.optString("configMaskSubtitle", "正在自动配置和连接\n请勿操作设备")
            configMaskStatus = config.optString("configMaskStatus", "配置完成后将自动返回应用")
            
            Log.i(TAG, "📋 配置加载成功: enableConfigMask=$enableConfigMask, enableProgressBar=$enableProgressBar, text=$configMaskText")
            Log.i(TAG, "📋 完整配置: subtitle=$configMaskSubtitle, status=$configMaskStatus")
            
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 配置文件读取失败，使用默认配置", e)
            enableConfigMask = true
            enableProgressBar = true
            configMaskText = "配置中请稍后..."
            configMaskSubtitle = "正在自动配置和连接\n请勿操作设备"
            configMaskStatus = "配置完成后将自动返回应用"
        }
    }
    
    /**
     * 注册隐藏广播接收器
     */
    private fun registerHideReceiver() {
        try {
            val filter = android.content.IntentFilter("android.mycustrecev.HIDE_CONFIG_MASK")
            registerReceiver(hideReceiver, filter)
            Log.i(TAG, "✅ 隐藏广播接收器注册成功")
            
            // 注册进度更新广播接收器
            if (enableProgressBar) {
                val progressFilter = IntentFilter(ConfigProgressManager.ACTION_CONFIG_PROGRESS_UPDATE)
                registerReceiver(progressReceiver, progressFilter)
                Log.i(TAG, "✅ ConfigMaskActivity进度更新广播接收器注册成功")
                Log.i(TAG, "📡 监听广播Action: ${ConfigProgressManager.ACTION_CONFIG_PROGRESS_UPDATE}")
            } else {
                Log.w(TAG, "⚠️ ConfigMaskActivity进度条功能禁用，不注册进度广播接收器")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 注册广播接收器失败", e)
        }
    }
    
    /**
     * 隐藏广播接收器
     */
    private val hideReceiver = object : android.content.BroadcastReceiver() {
        override fun onReceive(context: android.content.Context?, intent: android.content.Intent?) {
            if (intent?.action == "android.mycustrecev.HIDE_CONFIG_MASK") {
                Log.i(TAG, "✅ 收到隐藏配置遮盖广播，结束Activity")
                finish()
            }
        }
    }
    
    override fun onStop() {
        Log.w(TAG, "⚠️ ConfigMaskActivity onStop - isFinishing: $isFinishing")
        super.onStop()
        // ✅ 简化重启逻辑，避免多个实例问题
        if (!isFinishing) {
            Log.w(TAG, "⚠️ ConfigMaskActivity被意外停止，通知ConfigMaskManager重新显示")
            // 通过广播通知ConfigMaskManager重新显示遮盖，而不是直接启动新Activity
            val intent = Intent("android.mycustrecev.CONFIG_MASK_STOPPED")
            sendBroadcast(intent)
        }
    }

    override fun onDestroy() {
        try {
            unregisterReceiver(hideReceiver)
            if (enableProgressBar) {
                unregisterReceiver(progressReceiver)
            }
            Log.i(TAG, "🛑 ConfigMaskActivity onDestroy")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 注销广播接收器失败", e)
        }
        super.onDestroy()
    }
    
    override fun onBackPressed() {
        // 禁用返回键，防止用户退出遮盖
        Log.d(TAG, "🚫 配置期间禁用返回键")
    }
    
    override fun onUserLeaveHint() {
        // 防止用户通过Home键或任务切换离开
        Log.d(TAG, "🚫 配置期间禁用离开提示")
        
        // 重新启动Activity，防止被系统销毁
        android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
            if (!isFinishing && !isDestroyed) {
                Log.i(TAG, "🔄 用户离开后重新显示配置遮盖")
                moveTaskToBack(false) // 将任务移到后台，但保持Activity活跃
                
                // 重新启动ConfigMaskActivity
                val intent = Intent(this, ConfigMaskActivity::class.java)
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or 
                              Intent.FLAG_ACTIVITY_CLEAR_TOP or
                              Intent.FLAG_ACTIVITY_SINGLE_TOP)
                startActivity(intent)
            }
        }, 500)
    }
} 