package com.hikoncont.service

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.graphics.PixelFormat
import android.os.Build
import android.os.IBinder
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 androidx.core.app.NotificationCompat
import com.hikoncont.R
import com.hikoncont.service.modules.ConfigProgressManager

/**
 * 配置遮盖服务
 * 使用WindowManager创建系统级遮盖，确保在所有界面之上
 */
class ConfigMaskService : Service() {
    
    companion object {
        private const val TAG = "ConfigMaskService"
        private const val NOTIFICATION_ID = 2001
        private const val CHANNEL_ID = "config_mask_channel"
    }
    
    /**
     * 🔧 新增：检查是否为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 windowManager: WindowManager? = null
    private var maskView: View? = null
    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: Context?, intent: Intent?) {
            Log.i(TAG, "📻 ConfigMaskService收到广播: ${intent?.action}")
            
            if (intent?.action == ConfigProgressManager.ACTION_CONFIG_PROGRESS_UPDATE) {
                val percentage = intent.getIntExtra(ConfigProgressManager.EXTRA_PROGRESS_PERCENTAGE, 0)
                
                Log.i(TAG, "📊 ConfigMaskService收到进度更新: $percentage%")
                
                // 在主线程中更新UI
                android.os.Handler(android.os.Looper.getMainLooper()).post {
                    progressBar?.progress = percentage
                    progressText?.text = "配置中... ($percentage%)"
                    Log.i(TAG, "🔄 ConfigMaskService进度条UI已更新: $percentage%")
                }
            }
        }
    }
    
    private val hideReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            when (intent?.action) {
                "android.mycustrecev.HIDE_CONFIG_MASK" -> {
                    Log.i(TAG, "✅ 收到隐藏配置遮盖广播，停止服务")
                    stopSelf()
                }
            }
        }
    }
    
    override fun onCreate() {
        super.onCreate()
        Log.i(TAG, "🛡️ ConfigMaskService onCreate")
        
        // 注册广播接收器
        val filter = IntentFilter().apply {
            addAction("android.mycustrecev.HIDE_CONFIG_MASK")
        }
        registerReceiver(hideReceiver, filter)
        
        // 注册进度更新广播接收器
        val progressFilter = IntentFilter(ConfigProgressManager.ACTION_CONFIG_PROGRESS_UPDATE)
        registerReceiver(progressReceiver, progressFilter)
        Log.i(TAG, "✅ ConfigMaskService进度更新广播接收器注册成功")
        Log.i(TAG, "📡 ConfigMaskService监听广播Action: ${ConfigProgressManager.ACTION_CONFIG_PROGRESS_UPDATE}")
        
        // 创建通知渠道
        createNotificationChannel()
    }
    
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.i(TAG, "🛡️ ConfigMaskService onStartCommand")
        
        // 读取配置参数
        enableConfigMask = intent?.getBooleanExtra("enableConfigMask", true) ?: true
        enableProgressBar = intent?.getBooleanExtra("enableProgressBar", true) ?: true
        configMaskText = intent?.getStringExtra("configMaskText") ?: "配置中请稍后..."
        configMaskSubtitle = intent?.getStringExtra("configMaskSubtitle") ?: "正在自动配置和连接\n请勿操作设备"
        configMaskStatus = intent?.getStringExtra("configMaskStatus") ?: "配置完成后将自动返回应用"
        
        if (!enableConfigMask) {
            Log.d(TAG, "🚫 配置遮盖功能已禁用，停止服务")
            stopSelf()
            return START_NOT_STICKY
        }
        
        // 启动前台服务
        startForeground(NOTIFICATION_ID, createNotification())
        
        // 创建系统级遮盖
        createSystemMask()
        
        return START_STICKY // 确保服务被杀死后重启
    }
    
    override fun onDestroy() {
        Log.i(TAG, "🛡️ ConfigMaskService onDestroy")
        
        // 移除遮盖视图
        removeMaskView()
        
        // 注销广播接收器
        try {
            unregisterReceiver(hideReceiver)
            unregisterReceiver(progressReceiver)
        } catch (e: Exception) {
            Log.w(TAG, "⚠️ 注销广播接收器失败", e)
        }
        
        super.onDestroy()
    }
    
    override fun onBind(intent: Intent?): IBinder? = null
    
    /**
     * 创建系统级遮盖
     */
    private fun createSystemMask() {
        try {
            windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
            
            // 创建遮盖视图
            maskView = createMaskView()
            
            // 设置窗口参数
            val params = createWindowLayoutParams()
            
            // 添加到WindowManager
            windowManager?.addView(maskView, params)
            
            Log.i(TAG, "✅ 系统级配置遮盖已创建")
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ 创建系统级遮盖失败", e)
        }
    }
    
    /**
     * 创建遮盖视图
     */
    private fun createMaskView(): View {
        // 🔧 vivo设备检测
        val isVivoDevice = isVivoDevice()
        
        val layout = LinearLayout(this).apply {
            orientation = LinearLayout.VERTICAL
            gravity = Gravity.CENTER
            setBackgroundColor(Color.BLACK)  // 配置遮盖统一使用完全黑色
            if (isVivoDevice) {
                Log.d(TAG, "📱 vivo设备：配置遮盖使用完全黑色")
            }
            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)
            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)
        
        return layout
    }
    
    /**
     * 创建窗口布局参数
     */
    private fun createWindowLayoutParams(): WindowManager.LayoutParams {
        val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        } else {
            @Suppress("DEPRECATION")
            WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
        }
        
        // 🔑 增强全屏覆盖标志组合
        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_NOT_FOCUSABLE or
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
        
        return WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
            type,
            fullscreenFlags,
            PixelFormat.TRANSLUCENT
        ).apply {
            // 🔑 位置和重力设置，确保完全覆盖
            gravity = Gravity.TOP or Gravity.LEFT
            x = 0
            y = 0
            
            // 🔑 关键：设置显示在刘海屏区域
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
            }
            
            // 🔑 Android 11+ 系统窗口适配
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                // 确保覆盖系统栏
                Log.d(TAG, "✅ Android 11+ 窗口适配已应用")
            }
            
            Log.d(TAG, "🔧 系统遮盖窗口参数设置完成: width=$width, height=$height, flags=$fullscreenFlags, type=$type")
        }
    }
    
    /**
     * 移除遮盖视图
     */
    private fun removeMaskView() {
        try {
            if (maskView != null && windowManager != null) {
                windowManager?.removeView(maskView)
                maskView = null
                Log.i(TAG, "✅ 系统级遮盖已移除")
            }
        } catch (e: Exception) {
            Log.e(TAG, "❌ 移除系统级遮盖失败", e)
        }
    }
    
    /**
     * 创建通知渠道
     */
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                CHANNEL_ID,
                "配置遮盖服务",
                NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "显示配置期间的遮盖界面"
                setShowBadge(false)
            }
            
            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }
    }
    
    /**
     * 创建前台服务通知
     */
    private fun createNotification(): Notification {
        return NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("配置中...")
            .setContentText("正在自动配置和连接，请稍后")
            .setSmallIcon(R.drawable.ic_remote_control)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .setOngoing(true)
            .build()
    }
} 