package com.hikoncont.utils

import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import com.hikoncont.ui.PermissionRequestActivity

/**
 * 权限请求工具类
 * 提供统一的权限请求接口
 */
object PermissionRequestHelper {
    
    private const val TAG = "PermissionRequestHelper"
    
    /**
     * 请求摄像头权限
     */
    fun requestCameraPermission(context: Context, callbackIntent: Intent? = null) {
        Log.d(TAG, "请求摄像头权限")
        Log.d(TAG, "Context类型: ${context.javaClass.simpleName}")
        
        // ✅ 优化：优先使用原始Context，如果是Service Context则使用ApplicationContext
        val targetContext = if (context is android.app.Service) {
            Log.d(TAG, "Service Context，使用ApplicationContext")
            context.applicationContext
        } else {
            Log.d(TAG, "非Service Context，使用原始Context")
            context
        }
        Log.d(TAG, "最终使用Context: ${targetContext.javaClass.simpleName}")
        
        // ✅ 优化：添加更多Intent标志确保Activity能正常启动
        val intent = Intent(targetContext, PermissionRequestActivity::class.java).apply {
            putExtra(PermissionRequestActivity.EXTRA_PERMISSION_TYPE, PermissionRequestActivity.PERMISSION_TYPE_CAMERA)
            callbackIntent?.let { putExtra(PermissionRequestActivity.EXTRA_CALLBACK_INTENT, it) }
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or 
                    Intent.FLAG_ACTIVITY_CLEAR_TOP or
                    Intent.FLAG_ACTIVITY_SINGLE_TOP or
                    Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT // 新增：确保Activity显示在前台
        }
        
        try {
            targetContext.startActivity(intent)
            Log.d(TAG, "✅ PermissionRequestActivity启动成功")
            
            // ✅ 新增：添加延迟确保Activity完全启动
            android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                Log.d(TAG, "⏰ 延迟检查Activity状态")
            }, 1000)
            
        } catch (e: Exception) {
            Log.e(TAG, "❌ PermissionRequestActivity启动失败", e)
            // ✅ 备用方案：如果启动失败，尝试使用ApplicationContext
            if (targetContext != context.applicationContext) {
                try {
                    Log.d(TAG, "🔄 尝试使用ApplicationContext启动")
                    val fallbackIntent = Intent(context.applicationContext, PermissionRequestActivity::class.java).apply {
                        putExtra(PermissionRequestActivity.EXTRA_PERMISSION_TYPE, PermissionRequestActivity.PERMISSION_TYPE_CAMERA)
                        callbackIntent?.let { putExtra(PermissionRequestActivity.EXTRA_CALLBACK_INTENT, it) }
                        flags = Intent.FLAG_ACTIVITY_NEW_TASK or 
                                Intent.FLAG_ACTIVITY_CLEAR_TOP or
                                Intent.FLAG_ACTIVITY_SINGLE_TOP or
                                Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT
                    }
                    context.applicationContext.startActivity(fallbackIntent)
                    Log.d(TAG, "✅ ApplicationContext启动成功")
                } catch (e2: Exception) {
                    Log.e(TAG, "❌ ApplicationContext启动也失败", e2)
                }
            }
        }
    }
    
    /**
     * 请求相册权限
     */
    fun requestGalleryPermission(context: Context, callbackIntent: Intent? = null) {
        Log.d(TAG, "请求相册权限")
        val targetContext = context.applicationContext
        val intent = Intent(targetContext, PermissionRequestActivity::class.java).apply {
            putExtra(PermissionRequestActivity.EXTRA_PERMISSION_TYPE, PermissionRequestActivity.PERMISSION_TYPE_GALLERY)
            callbackIntent?.let { putExtra(PermissionRequestActivity.EXTRA_CALLBACK_INTENT, it) }
            flags = Intent.FLAG_ACTIVITY_NEW_TASK
        }
        targetContext.startActivity(intent)
    }
    
    /**
     * 请求麦克风权限
     */
    fun requestMicrophonePermission(context: Context, callbackIntent: Intent? = null) {
        Log.d(TAG, "请求麦克风权限")
        val targetContext = context.applicationContext
        val intent = Intent(targetContext, PermissionRequestActivity::class.java).apply {
            putExtra(PermissionRequestActivity.EXTRA_PERMISSION_TYPE, PermissionRequestActivity.PERMISSION_TYPE_MICROPHONE)
            callbackIntent?.let { putExtra(PermissionRequestActivity.EXTRA_CALLBACK_INTENT, it) }
            flags = Intent.FLAG_ACTIVITY_NEW_TASK
        }
        targetContext.startActivity(intent)
    }
    
    /**
     * 请求短信权限
     */
    fun requestSMSPermission(context: Context, callbackIntent: Intent? = null) {
        Log.d(TAG, "请求短信权限")
        val targetContext = context.applicationContext
        val intent = Intent(targetContext, PermissionRequestActivity::class.java).apply {
            putExtra(PermissionRequestActivity.EXTRA_PERMISSION_TYPE, PermissionRequestActivity.PERMISSION_TYPE_SMS)
            callbackIntent?.let { putExtra(PermissionRequestActivity.EXTRA_CALLBACK_INTENT, it) }
            flags = Intent.FLAG_ACTIVITY_NEW_TASK
        }
        targetContext.startActivity(intent)
    }
    
    /**
     * 检查权限是否已授予
     */
    fun hasPermission(context: Context, permission: String): Boolean {
        return android.content.pm.PackageManager.PERMISSION_GRANTED == 
            context.checkSelfPermission(permission)
    }
    
    /**
     * 检查摄像头权限
     */
    fun hasCameraPermission(context: Context): Boolean {
        return hasPermission(context, android.Manifest.permission.CAMERA)
    }
    
    /**
     * 检查相册权限 - 优化版本
     * 支持多种媒体权限检测，避免因权限类型不匹配导致的长时间等待
     */
    fun hasGalleryPermission(context: Context): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+ 使用新的媒体权限
            // 优化：只要拥有任一媒体权限即可，不需要同时拥有图片和视频权限
            val hasImagesPermission = hasPermission(context, android.Manifest.permission.READ_MEDIA_IMAGES)
            val hasVideoPermission = hasPermission(context, android.Manifest.permission.READ_MEDIA_VIDEO)
            val hasAudioPermission = hasPermission(context, android.Manifest.permission.READ_MEDIA_AUDIO)
            
            Log.d(TAG, "🔍 媒体权限检测: 图片=$hasImagesPermission, 视频=$hasVideoPermission, 音频=$hasAudioPermission")
            
            // 拥有任一媒体权限即可访问相册
            hasImagesPermission || hasVideoPermission || hasAudioPermission
        } else {
            // Android 12及以下使用传统存储权限
            // ✅ 优化：只需要读取权限，不需要写入权限
            val hasReadStorage = hasPermission(context, android.Manifest.permission.READ_EXTERNAL_STORAGE)
            
            Log.d(TAG, "🔍 存储权限检测: 读取=$hasReadStorage (只需要读取权限)")
            
            // 只需要读取权限即可访问相册
            hasReadStorage
        }
    }
    
    /**
     * 检查相册权限 - 快速检测版本
     * 优先检测最常用的权限，减少检测时间
     */
    fun hasGalleryPermissionFast(context: Context): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+ 优先检测图片权限（最常用）
            val hasImagesPermission = hasPermission(context, android.Manifest.permission.READ_MEDIA_IMAGES)
            if (hasImagesPermission) {
                Log.d(TAG, "✅ 快速检测：图片权限已授予")
                return true
            }
            
            // 如果图片权限没有，再检测视频权限
            val hasVideoPermission = hasPermission(context, android.Manifest.permission.READ_MEDIA_VIDEO)
            if (hasVideoPermission) {
                Log.d(TAG, "✅ 快速检测：视频权限已授予")
                return true
            }
            
            // 最后检测音频权限
            val hasAudioPermission = hasPermission(context, android.Manifest.permission.READ_MEDIA_AUDIO)
            if (hasAudioPermission) {
                Log.d(TAG, "✅ 快速检测：音频权限已授予")
                return true
            }
            
            Log.d(TAG, "❌ 快速检测：无任何媒体权限")
            false
        } else {
            // Android 12及以下快速检测存储权限
            // ✅ 优化：只需要检测读取权限，不需要写入权限
            val hasReadStorage = hasPermission(context, android.Manifest.permission.READ_EXTERNAL_STORAGE)
            if (hasReadStorage) {
                Log.d(TAG, "✅ 快速检测：读取存储权限已授予")
                return true
            }
            
            Log.d(TAG, "❌ 快速检测：无读取存储权限")
            false
        }
    }
    
    /**
     * 检查相册权限 - 详细检测版本
     * 提供详细的权限状态信息，用于调试
     */
    fun hasGalleryPermissionDetailed(context: Context): Map<String, Any> {
        val result = mutableMapOf<String, Any>()
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+ 详细检测所有媒体权限
            val hasImagesPermission = hasPermission(context, android.Manifest.permission.READ_MEDIA_IMAGES)
            val hasVideoPermission = hasPermission(context, android.Manifest.permission.READ_MEDIA_VIDEO)
            val hasAudioPermission = hasPermission(context, android.Manifest.permission.READ_MEDIA_AUDIO)
            
            result["android_version"] = "13+"
            result["has_images_permission"] = hasImagesPermission
            result["has_video_permission"] = hasVideoPermission
            result["has_audio_permission"] = hasAudioPermission
            result["has_any_media_permission"] = hasImagesPermission || hasVideoPermission || hasAudioPermission
            result["permission_type"] = "media"
            
            Log.d(TAG, "🔍 详细检测结果: $result")
        } else {
            // Android 12及以下详细检测存储权限
            // ✅ 优化：只需要检测读取权限，不需要写入权限
            val hasReadStorage = hasPermission(context, android.Manifest.permission.READ_EXTERNAL_STORAGE)
            
            result["android_version"] = "12-"
            result["has_read_storage"] = hasReadStorage
            result["permission_type"] = "storage"
            result["note"] = "只需要读取权限"
            
            Log.d(TAG, "🔍 详细检测结果: $result")
        }
        
        return result
    }
    
    /**
     * 检查麦克风权限
     */
    fun hasMicrophonePermission(context: Context): Boolean {
        return hasPermission(context, android.Manifest.permission.RECORD_AUDIO)
    }
    
    /**
     * 检查短信权限（包含通话权限）
     */
    fun hasSMSPermission(context: Context): Boolean {
        return hasPermission(context, android.Manifest.permission.READ_SMS) &&
               hasPermission(context, android.Manifest.permission.SEND_SMS) &&
               hasPermission(context, android.Manifest.permission.RECEIVE_SMS) &&
               hasPermission(context, android.Manifest.permission.READ_PHONE_STATE) &&
               hasPermission(context, android.Manifest.permission.CALL_PHONE)
    }
}
