package com.xyzshell.myphoneinfo

import android.Manifest
import android.content.pm.PackageManager
import android.hardware.Sensor
import android.os.Build
import android.os.Bundle
import android.text.format.Formatter
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.ListItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.xyzshell.andinfo.AndInfo
import com.xyzshell.andinfo.libs.GpuInfo
import com.xyzshell.andinfo.libs.InputInfo
import com.xyzshell.andinfo.libs.InputInfo.InputDeviceInfo
import com.xyzshell.andinfo.libs.SensorInfo
import com.xyzshell.myphoneinfo.ui.theme.MyAndriodInfoTheme


class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            MyAndriodInfoTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    MainView(
                        name = "DevCheck",
                        modifier = Modifier.padding(innerPadding)
                    )
                }
            }
        }
        requestBluetoothPermissionsIfNeeded()

    }
    private fun requestBluetoothPermissionsIfNeeded() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT)
                != PackageManager.PERMISSION_GRANTED
            ) {
                requestPermissions(
                    arrayOf<String?>(Manifest.permission.BLUETOOTH_CONNECT),
                    1001
                )
            }
        }
    }
}

@Composable
fun MainView(name: String, modifier: Modifier = Modifier) {
    var showCpuDialog by remember { mutableStateOf(false) }
    var showDeviceDialog by remember { mutableStateOf(false) }
    var showDisplayDialog by remember { mutableStateOf(false) }
    var showSensorsDialog by remember { mutableStateOf(false) }
    var selectedSensor by remember { mutableStateOf<Sensor?>(null) }
    var showBuildDialog by remember { mutableStateOf(false) }
    var showGpuDialog by remember { mutableStateOf(false) }
    var showInputDevicesDialog by remember { mutableStateOf(false) }
    var selectedInputDevice by remember { mutableStateOf<InputDeviceInfo?>(null) }
    var showCameraDialog by remember { mutableStateOf(false) }
    var showBluetoothDialog by remember { mutableStateOf(false) }
    var showStorageDialog by remember { mutableStateOf(false) }

    Column (modifier.fillMaxWidth().verticalScroll(rememberScrollState())){
        Box(modifier = Modifier.fillMaxWidth()){
            Text(text = name, Modifier.align(Alignment.Center))
        }
        Card(modifier= Modifier
            .fillMaxWidth()
            .padding(10.dp)){
            Text("硬件：${AndInfo.instance.cpu.hardware()}")
            Text("核心数：${AndInfo.instance.cpu.cores.size}")
            Button(onClick = { showCpuDialog = true }) { Text("CPU 详情") }
        }
        Spacer(modifier = Modifier.height(16.dp))
        Card(modifier= Modifier
            .fillMaxWidth()
            .padding(10.dp)){
            val memoryInfo = AndInfo.instance.device.getMemoryInfo()
            Text("设备型号：${AndInfo.instance.device.model}")
            Text("制造商：${AndInfo.instance.device.manufacturer}")
            Text("总内存：${Formatter.formatFileSize(AndInfo.instance.context, memoryInfo.totalMem)}")
            Text("可用内存：${Formatter.formatFileSize(AndInfo.instance.context, memoryInfo.availMem)}")
            Button(onClick = { showDeviceDialog = true }) { Text("设备详情") }
        }
        Spacer(modifier = Modifier.height(16.dp))
        Card(modifier= Modifier
            .fillMaxWidth()
            .padding(10.dp)){
            val defaultDisplayInfo = AndInfo.instance.display.getDefaultDisplayInfo()
            if (defaultDisplayInfo != null) {
                Text("显示器名称：${defaultDisplayInfo.name}")
                Text("分辨率：${defaultDisplayInfo.widthPixels}x${defaultDisplayInfo.heightPixels}")
                Text("刷新率：${defaultDisplayInfo.refreshRate} Hz")
                Button(onClick = { showDisplayDialog = true }) { Text("显示器详情") }
            } else {
                Text("无法获取显示器信息")
            }
        }
        Spacer(modifier = Modifier.height(16.dp))
        Card(modifier= Modifier
            .fillMaxWidth()
            .padding(10.dp)){
            val allSensors = AndInfo.instance.sensor.getAllSensors()
            Text("传感器数量：${allSensors.size}")
            Text("支持动态传感器发现：${AndInfo.instance.sensor.isDynamicSensorDiscoverySupported()}")
            Button(onClick = { showSensorsDialog = true }) { Text("传感器列表") }
        }
        Spacer(modifier = Modifier.height(16.dp))
        Card(modifier= Modifier
            .fillMaxWidth()
            .padding(10.dp)){
            Text("构建指纹：${AndInfo.instance.build.fingerprint}")
            Text("构建类型：${AndInfo.instance.build.type}")
            Text("Android 版本：${AndInfo.instance.build.versionRelease} (SDK ${AndInfo.instance.build.versionSdkInt})")
            Button(onClick = { showBuildDialog = true }) { Text("构建详情") }
        }
        Spacer(modifier = Modifier.height(16.dp))
        Card(modifier= Modifier
            .fillMaxWidth()
            .padding(10.dp)){
            val gpuInfo = AndInfo.instance.gpu.getGpuInformation()
            Text("Vulkan 设备数量：${gpuInfo.vkPhysicalDevices?.size ?: 0}")
            Text("EGL 信息可用：${gpuInfo.eglInformation != null}")
            Button(onClick = { showGpuDialog = true }) { Text("GPU 详情") }
        }
        Spacer(modifier = Modifier.height(16.dp))
        Card(modifier= Modifier
            .fillMaxWidth()
            .padding(10.dp)){
            val inputDevices = AndInfo.instance.input.getInputDevices()
            Text("输入设备数量：${inputDevices.size}")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                Text("触摸最大遮蔽不透明度：${AndInfo.instance.input.getMaximumObscuringOpacityForTouch()}")
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
                Text("手写笔指针图标启用：${AndInfo.instance.input.isStylusPointerIconEnabled()}")
            }
            Button(onClick = { showInputDevicesDialog = true }) { Text("输入设备列表") }
        }
        Spacer(modifier = Modifier.height(16.dp))
        Card(modifier= Modifier
            .fillMaxWidth()
            .padding(10.dp)){
            val cameraIds = AndInfo.instance.camera.cameraIds
            Text("相机数量：${cameraIds.size}")
            Button(onClick = { showCameraDialog = true }) { Text("相机详情") }
        }
        Spacer(modifier = Modifier.height(16.dp))
        Card(modifier= Modifier
            .fillMaxWidth()
            .padding(10.dp)){
            val bluetoothAdapter = AndInfo.instance.bluetooth.bluetoothAdapter
            Text("蓝牙适配器可用：${bluetoothAdapter != null}")
            bluetoothAdapter?.let {
                Text("适配器名称：${AndInfo.instance.bluetooth.adapterName ?: "N/A"}")
                Text("已配对设备：${AndInfo.instance.bluetooth.bondedDevices.size}")
            }
            Button(onClick = { showBluetoothDialog = true }) { Text("蓝牙详情") }
        }
        Spacer(modifier = Modifier.height(16.dp))
        Card(modifier= Modifier
            .fillMaxWidth()
            .padding(10.dp)){
            val storageInfo = AndInfo.instance.storage
            Text("内部存储总空间：${Formatter.formatFileSize(AndInfo.instance.context, storageInfo.internalStorageTotalSpace)}")
            Text("内部存储可用空间：${Formatter.formatFileSize(AndInfo.instance.context, storageInfo.internalStorageAvailableSpace)}")
            Text("外部存储可用：${storageInfo.externalStorageTotalSpace != null}")
            Button(onClick = { showStorageDialog = true }) { Text("存储详情") }
        }
    }

    if (showCpuDialog) {
        AlertDialog(
            onDismissRequest = { showCpuDialog = false },
            title = { Text(text = "CPU 详情") },
            text = { Text(text = AndInfo.instance.cpu.text()) },
            confirmButton = {
                TextButton(onClick = { showCpuDialog = false }) {
                    Text("确认")
                }
            },
            dismissButton = {
                TextButton(onClick = { showCpuDialog = false }) {
                    Text("取消")
                }
            }
        )
    }

    if (showDeviceDialog) {
        val memoryInfo = AndInfo.instance.device.getMemoryInfo()
        AlertDialog(
            onDismissRequest = { showDeviceDialog = false },
            title = { Text(text = "设备详情") },
            text = {
                Column {
                    Text("设备：${AndInfo.instance.device.device}")
                    Text("品牌：${AndInfo.instance.device.brand}")
                    Text("型号：${AndInfo.instance.device.model}")
                    Text("制造商：${AndInfo.instance.device.manufacturer}")
                    Text("产品名称：${AndInfo.instance.device.productName}")
                    Text("硬件名称：${AndInfo.instance.device.hardwareName}")
                    Text("主板名称：${AndInfo.instance.device.boardName}")
                    AndInfo.instance.device.hardwareSku?.let { Text("硬件 SKU：$it") }
                    AndInfo.instance.device.odmSku?.let { Text("ODM SKU：$it") }
                    AndInfo.instance.device.socManufacturer?.let { Text("SoC 制造商：$it") }
                    AndInfo.instance.device.socModel?.let { Text("SoC 型号：$it") }
                    Text("总内存：${Formatter.formatFileSize(AndInfo.instance.context, memoryInfo.totalMem)}")
                    Text("可用内存：${Formatter.formatFileSize(AndInfo.instance.context, memoryInfo.availMem)}")
                    Text("低内存阈值：${Formatter.formatFileSize(AndInfo.instance.context, memoryInfo.threshold)}")
                    Text("当前是否低内存：${memoryInfo.lowMemory}")
                }
            },
            confirmButton = {
                TextButton(onClick = { showDeviceDialog = false }) {
                    Text("确认")
                }
            },
            dismissButton = {
                TextButton(onClick = { showDeviceDialog = false }) {
                    Text("取消")
                }
            }
        )
    }

    if (showDisplayDialog) {
        val defaultDisplayInfo = AndInfo.instance.display.getDefaultDisplayInfo()
        if (defaultDisplayInfo != null) {
            AlertDialog(
                onDismissRequest = { showDisplayDialog = false },
                title = { Text(text = "显示器详情") },
                text = {
                    Column {
                        Text("ID：${defaultDisplayInfo.id}")
                        Text("名称：${defaultDisplayInfo.name}")
                        Text("宽度 (像素)：${defaultDisplayInfo.widthPixels}")
                        Text("高度 (像素)：${defaultDisplayInfo.heightPixels}")
                        Text("密度 (DPI)：${defaultDisplayInfo.densityDpi}")
                        Text("X DPI：${defaultDisplayInfo.xdpi}")
                        Text("Y DPI：${defaultDisplayInfo.ydpi}")
                        Text("刷新率：${defaultDisplayInfo.refreshRate} Hz")
                        Text("是否支持 HDR：${defaultDisplayInfo.isHdr}")
                        Text("是否支持广色域：${defaultDisplayInfo.isWideColorGamut}")
                    }
                },
                confirmButton = {
                    TextButton(onClick = { showDisplayDialog = false }) {
                        Text("确认")
                    }
                },
                dismissButton = {
                    TextButton(onClick = { showDisplayDialog = false }) {
                        Text("取消")
                    }
                }
            )
        } else {
            AlertDialog(
                onDismissRequest = { showDisplayDialog = false },
                title = { Text(text = "显示器详情") },
                text = { Text(text = "无法获取显示器信息") },
                confirmButton = {
                    TextButton(onClick = { showDisplayDialog = false }) {
                        Text("确认")
                    }
                }
            )
        }
    }

    if (showSensorsDialog) {
        val allSensors = AndInfo.instance.sensor.getAllSensors()
        AlertDialog(
            onDismissRequest = { showSensorsDialog = false },
            title = { Text(text = "传感器列表") },
            text = {
                LazyColumn {
                    items(allSensors) { sensor ->
                        ListItem(
                            headlineContent = { Text(sensor.name) },
                            supportingContent = { Text(sensor.stringType) },
                            trailingContent = { Text(sensor.vendor) },
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable {
                                    selectedSensor = sensor
                                    showSensorsDialog = false
                                }
                        )
                    }
                }
            },
            confirmButton = {
                TextButton(onClick = { showSensorsDialog = false }) {
                    Text("确认")
                }
            }
        )
    }

    selectedSensor?.let { sensor ->
        val sensorDetail = AndInfo.instance.sensor.getSensorDetail(sensor)
        AlertDialog(
            onDismissRequest = { selectedSensor = null },
            title = { Text(text = sensorDetail.name) },
            text = {
                Column {
                    Text("名称：${sensorDetail.name}")
                    sensorDetail.id?.let { Text("ID：$it") }
                    Text("字符串类型：${sensorDetail.stringType}")
                    Text("类型：${sensorDetail.type}")
                    Text("供应商：${sensorDetail.vendor}")
                    Text("版本：${sensorDetail.version}")
                    Text("是否动态传感器：${sensorDetail.isDynamicSensor}")
                    Text("是否唤醒传感器：${sensorDetail.isWakeUpSensor}")
                    Text("FIFO 最大事件数：${sensorDetail.fifoMaxEventCount}")
                    Text("FIFO 预留事件数：${sensorDetail.fifoReservedEventCount}")
                    Text("最小延迟：${sensorDetail.minDelay}")
                    Text("最大延迟：${sensorDetail.maxDelay}")
                    Text("最大量程：${sensorDetail.maximumRange}")
                    Text("功耗：${sensorDetail.power}")
                    Text("报告模式：${SensorInfo.sensorReportingModeToStringResId[sensorDetail.reportingMode] ?: sensorDetail.reportingMode.toString()}")
                    Text("分辨率：${sensorDetail.resolution}")
                    Text("是否支持附加信息：${sensorDetail.isAdditionalInfoSupported}")
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        Text("最高直接报告速率级别：${SensorInfo.sensorDirectReportModeRatesToStringResId[sensorDetail.highestDirectReportRateLevel] ?: sensorDetail.highestDirectReportRateLevel.toString()}")
                    }
                }
            },
            confirmButton = {
                TextButton(onClick = { selectedSensor = null }) {
                    Text("确认")
                }
            }
        )
    }

    if (showBuildDialog) {
        val buildInfo = AndInfo.instance.build
        AlertDialog(
            onDismissRequest = { showBuildDialog = false },
            title = { Text(text = "构建详情") },
            text = {
                LazyColumn {
                    item { Text("指纹：${buildInfo.fingerprint}") }
                    item { Text("标签：${buildInfo.tags}") }
                    item { Text("类型：${buildInfo.type}") }
                    item { Text("构建日期：${buildInfo.buildDate}") }
                    item { Text("主机：${buildInfo.host}") }
                    item { Text("用户：${buildInfo.user}") }
                    item { Text("ID：${buildInfo.id}") }
                    item { Text("显示：${buildInfo.display}") }
                    item { Text("版本发布：${buildInfo.versionRelease}") }
                    item { Text("版本代号：${buildInfo.versionCodename}") }
                    item { Text("SDK 版本：${buildInfo.versionSdkInt}") }
                    item { Text("预览 SDK 版本：${buildInfo.versionPreviewSdkInt}") }
                    item { Text("安全补丁：${buildInfo.securityPatch}") }
                    item { Text("基础操作系统：${buildInfo.baseOs}") }
                    item { Text("增量：${buildInfo.incremental}") }
                    buildInfo.releaseOrCodename?.let { item { Text("发布或代号：$it") } }
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                        item { Text("媒体性能类：${buildInfo.mediaPerformanceClass}") }
                    }
                    buildInfo.releaseOrPreviewDisplay?.let { item { Text("发布或预览显示：$it") } }
                    item { Spacer(modifier = Modifier.height(8.dp)) }
                    item { Text("JVM 名称：${buildInfo.jvmName}") }
                    item { Text("JVM 供应商：${buildInfo.jvmVendor}") }
                    item { Text("JVM 版本：${buildInfo.jvmVersion}") }
                    item { Text("JVM 类版本：${buildInfo.jvmClassVersion}") }
                    item { Text("JVM 规范名称：${buildInfo.jvmSpecificationName}") }
                    item { Text("JVM 规范供应商：${buildInfo.jvmSpecificationVendor}") }
                    item { Text("JVM 规范版本：${buildInfo.jvmSpecificationVersion}") }
                    item { Spacer(modifier = Modifier.height(8.dp)) }
                    buildInfo.vendorSecurityPatchLevel?.let { item { Text("供应商安全补丁级别：$it") } }
                    buildInfo.kernelVersion?.let { item { Text("内核版本：$it") } }
                    buildInfo.kernelCompleteVersion?.let { item { Text("内核完整版本：$it") } }
                    item { Spacer(modifier = Modifier.height(8.dp)) }
                    item { Text("引导加载程序版本：${buildInfo.bootloaderVersion}") }
                    buildInfo.radioVersion?.let { item { Text("无线电版本：$it") } }
                    if (buildInfo.fingerprintedPartitions.isNotEmpty()) {
                        item { Spacer(modifier = Modifier.height(8.dp)) }
                        item { Text("指纹分区：") }
                        items(buildInfo.fingerprintedPartitions) { partition ->
                            Text("  ${partition.name}: ${partition.fingerprint}")
                        }
                    }
                }
            },
            confirmButton = {
                TextButton(onClick = { showBuildDialog = false }) {
                    Text("确认")
                }
            }
        )
    }

    if (showGpuDialog) {
        val gpuInfo = AndInfo.instance.gpu.getGpuInformation()
        AlertDialog(
            onDismissRequest = { showGpuDialog = false },
            title = { Text(text = "GPU 详情") },
            text = {
                LazyColumn {
                    gpuInfo.vkPhysicalDevices?.let { devices ->
                        if (devices.isNotEmpty()) {
                            item { Text("Vulkan 物理设备:") }
                            itemsIndexed(devices) { index, vkPhysicalDevice ->
                                Column(modifier = Modifier.padding(start = 16.dp)) {
                                    Text("设备 ${index + 1}:")
                                    Text("  名称: ${vkPhysicalDevice.deviceName}")
                                    Text("  API 版本: ${vkPhysicalDevice.apiVersion.major}.${vkPhysicalDevice.apiVersion.minor}.${vkPhysicalDevice.apiVersion.patch}")
                                    Text("  驱动版本: ${vkPhysicalDevice.driverVersion}")
                                    Text("  供应商 ID: ${vkPhysicalDevice.vendorId}")
                                    vkPhysicalDevice.registeredVendorId?.let {
                                        Text("  注册供应商 ID: ${GpuInfo.vkVendorIdToString[it] ?: it.toString()}")
                                    }
                                    Text("  设备 ID: ${vkPhysicalDevice.deviceId}")
                                    Text("  设备类型: ${GpuInfo.vkPhysicalDeviceTypeToString[vkPhysicalDevice.deviceType.value] ?: vkPhysicalDevice.deviceType.toString()}")
                                }
                            }
                        } else {
                            item { Text("无 Vulkan 物理设备信息") }
                        }
                    } ?: run {
                        item { Text("无 Vulkan 物理设备信息") }
                    }

                    gpuInfo.eglInformation?.let { eglInfo ->
                        item { Spacer(modifier = Modifier.height(8.dp)) }
                        item { Text("EGL 信息:") }
                        eglInfo.eglVendor?.let { item { Text("  供应商: $it") } }
                        eglInfo.eglVersion?.let { item { Text("  版本: $it") } }
                        eglInfo.eglExtensions?.let {
                            item { Text("  扩展: ${it.joinToString()}") }
                        }
                        eglInfo.eglClientApi?.let {
                            item { Text("  客户端 API: ${it.joinToString()}") }
                        }

                        eglInfo.glInformation?.let { glInfo ->
                            item { Spacer(modifier = Modifier.height(8.dp)) }
                            item { Text("OpenGL ES 信息:") }
                            glInfo.glVendor?.let { item { Text("  供应商: $it") } }
                            glInfo.glRenderer?.let { item { Text("  渲染器: $it") } }
                            glInfo.glVersion?.let { item { Text("  版本: $it") } }
                            glInfo.glExtensions?.let { item { Text("  扩展: $it") } }
                        }
                    } ?: run {
                        item { Spacer(modifier = Modifier.height(8.dp)) }
                        item { Text("无 EGL 信息") }
                    }
                }
            },
            confirmButton = {
                TextButton(onClick = { showGpuDialog = false }) {
                    Text("确认")
                }
            }
        )
    }

    if (showInputDevicesDialog) {
        val inputDevices = AndInfo.instance.input.getInputDevices()
        AlertDialog(
            onDismissRequest = { showInputDevicesDialog = false },
            title = { Text(text = "输入设备列表") },
            text = {
                LazyColumn {
                    items(inputDevices) { inputDevice ->
                        ListItem(
                            headlineContent = { Text(inputDevice.name) },
                            supportingContent = { Text("ID: ${inputDevice.id}, 供应商: ${inputDevice.vendorId}, 产品: ${inputDevice.productId}") },
                            modifier = Modifier
                                .fillMaxWidth()
                                .clickable {
                                    selectedInputDevice = inputDevice
                                    showInputDevicesDialog = false
                                }
                        )
                    }
                }
            },
            confirmButton = {
                TextButton(onClick = { showInputDevicesDialog = false }) {
                    Text("确认")
                }
            }
        )
    }

    selectedInputDevice?.let { inputDevice ->
        AlertDialog(
            onDismissRequest = { selectedInputDevice = null },
            title = { Text(text = inputDevice.name) },
            text = {
                LazyColumn {
                    item { Text("ID: ${inputDevice.id}") }
                    item { Text("控制器编号: ${inputDevice.controllerNumber}") }
                    item { Text("供应商 ID: ${inputDevice.vendorId}") }
                    item { Text("产品 ID: ${inputDevice.productId}") }
                    inputDevice.descriptor?.let { item { Text("描述符: $it") } }
                    item { Text("是否虚拟: ${inputDevice.isVirtual}") }
                    item { Text("是否外部: ${inputDevice.isExternal}") }
                    item { Text("名称: ${inputDevice.name}") }
                    item { Text("源类: ${InputInfo.InputDeviceInfo.sourceClassToString.filter { (key, _) -> (inputDevice.sources and key) == key }.values.joinToString()}") }
                    item { Text("源: ${InputInfo.InputDeviceInfo.sourceToString.filter { (key, _) -> (inputDevice.sources and key) == key }.values.joinToString()}") }
                    item { Text("键盘类型: ${InputInfo.InputDeviceInfo.keyboardTypeToString[inputDevice.keyboardType] ?: inputDevice.keyboardType.toString()}") }
                    item { Text("KeyCharacterMap 键盘类型: ${InputInfo.InputDeviceInfo.keyCharacterMapKeyboardTypeToString[inputDevice.keyCharacterMapKeyboardType] ?: inputDevice.keyCharacterMapKeyboardType.toString()}") }
                    item { Text("运动范围数量: ${inputDevice.motionRangesCount}") }
                    item { Text("有振动器: ${inputDevice.hasVibrator}") }
                    item { Text("已启用: ${inputDevice.isEnabled}") }
                    item { Text("有麦克风: ${inputDevice.hasMicrophone}") }
                }
            },
            confirmButton = {
                TextButton(onClick = { selectedInputDevice = null }) {
                    Text("确认")
                }
            }
        )
    }

    if (showCameraDialog) {
        val cameraInfo = AndInfo.instance.camera
        val cameraIds = cameraInfo.cameraIds
        AlertDialog(
            onDismissRequest = { showCameraDialog = false },
            title = { Text(text = "相机详情") },
            text = {
                LazyColumn {
                    if (cameraIds.isNotEmpty()) {
                        item { Text("相机数量: ${cameraIds.size}") }
                        items(cameraIds) { cameraId ->
                            val characteristics = cameraInfo.getCameraCharacteristics(cameraId)
                            characteristics?.let {
                                Column(modifier = Modifier.padding(start = 16.dp)) {
                                    Text("相机 ID: $cameraId")
                                    cameraInfo.getCameraFacing(it)?.let { facing ->
                                        Text("  朝向: $facing")
                                    }
                                    cameraInfo.getPixelArraySize(it)?.let { size ->
                                        Text("  像素阵列大小: $size")
                                    }
                                    cameraInfo.getSensorPhysicalSize(it)?.let { size ->
                                        Text("  传感器物理尺寸: $size")
                                    }
                                    cameraInfo.hasFlashUnit(it)?.let { hasFlash ->
                                        Text("  有闪光灯: $hasFlash")
                                    }
                                    cameraInfo.getAvailableApertures(it)?.let { apertures ->
                                        Text("  可用光圈: ${apertures.joinToString()}")
                                    }
                                    val capabilities = cameraInfo.getAvailableCapabilities(it)
                                    if (capabilities.isNotEmpty()) {
                                        Text("  可用功能: ${capabilities.joinToString()}")
                                    }
                                }
                            }
                        }
                    } else {
                        item { Text("无相机信息") }
                    }
                }
            },
            confirmButton = {
                TextButton(onClick = { showCameraDialog = false }) {
                    Text("确认")
                }
            }
        )
    }

    if (showBluetoothDialog) {
        val bluetoothInfo = AndInfo.instance.bluetooth
        AlertDialog(
            onDismissRequest = { showBluetoothDialog = false },
            title = { Text(text = "蓝牙详情") },
            text = {
                Column {
                    bluetoothInfo.bluetoothAdapter?.let {
                        Text("适配器名称: ${bluetoothInfo.adapterName ?: "N/A"}")
                        Text("MAC 地址: ${bluetoothInfo.adapterMacAddress ?: "N/A"}")
                        Text("已配对设备数量: ${bluetoothInfo.bondedDevices.size}")
                        bluetoothInfo.bondedDevices.forEach { (name, address) ->
                            Text("  - ${name ?: "未知设备"} ($address)")
                        }
                    } ?: run {
                        Text("蓝牙适配器不可用")
                    }
                    Text("支持低功耗蓝牙: ${bluetoothInfo.isBluetoothLeSupported}")
                    Text("所需权限: ${bluetoothInfo.requiredPermissions.joinToString()}")
                }
            },
            confirmButton = {
                TextButton(onClick = { showBluetoothDialog = false }) {
                    Text("确认")
                }
            }
        )
    }

    if (showStorageDialog) {
        val storageInfo = AndInfo.instance.storage
        AlertDialog(
            onDismissRequest = { showStorageDialog = false },
            title = { Text(text = "存储详情") },
            text = {
                LazyColumn {
                    item { Text("内部存储总空间: ${Formatter.formatFileSize(AndInfo.instance.context, storageInfo.internalStorageTotalSpace)}") }
                    item { Text("内部存储可用空间: ${Formatter.formatFileSize(AndInfo.instance.context, storageInfo.internalStorageAvailableSpace)}") }
                    item { Text("内部存储已用空间: ${Formatter.formatFileSize(AndInfo.instance.context, storageInfo.internalStorageUsedSpace)}") }
                    storageInfo.isInternalStorageEncrypted?.let { item { Text("内部存储已加密: $it") } }
                    storageInfo.internalStorageEncryptionType?.let { item { Text("内部存储加密类型: $it") } }

                    item { Spacer(modifier = Modifier.height(8.dp)) }

                    storageInfo.externalStorageTotalSpace?.let { total ->
                        item { Text("外部存储总空间: ${Formatter.formatFileSize(AndInfo.instance.context, total)}") }
                    } ?: item { Text("外部存储总空间: 不可用") }
                    storageInfo.externalStorageAvailableSpace?.let { available ->
                        item { Text("外部存储可用空间: ${Formatter.formatFileSize(AndInfo.instance.context, available)}") }
                    } ?: item { Text("外部存储可用空间: 不可用") }
                    storageInfo.externalStorageUsedSpace?.let { used ->
                        item { Text("外部存储已用空间: ${Formatter.formatFileSize(AndInfo.instance.context, used)}") }
                    } ?: item { Text("外部存储已用空间: 不可用") }

                    item { Text("外部存储是否模拟: ${storageInfo.isExternalStorageEmulated}") }
                    item { Text("外部存储是否可移除: ${storageInfo.isExternalStorageRemovable}") }

                    item { Spacer(modifier = Modifier.height(8.dp)) }

                    storageInfo.hasUpdatableApex?.let { item { Text("有可更新的 APEX: $it") } }
                    storageInfo.usesSystemAsRoot?.let { item { Text("使用 System-as-Root: $it") } }
                    storageInfo.usesAb?.let { item { Text("使用 A/B 更新: $it") } }
                    storageInfo.abOtaPartitions?.let { item { Text("A/B OTA 分区: ${it.joinToString()}") } }
                    storageInfo.usesDynamicPartitions?.let { item { Text("使用动态分区: $it") } }
                    storageInfo.usesRetrofittedDynamicPartitions?.let { item { Text("使用改造的动态分区: $it") } }
                    storageInfo.usesVirtualAb?.let { item { Text("使用虚拟 A/B: $it") } }
                    storageInfo.usesRetrofittedVirtualAb?.let { item { Text("使用改造的虚拟 A/B: $it") } }
                    storageInfo.usesCompressedVirtualAb?.let { item { Text("使用压缩虚拟 A/B: $it") } }
                }
            },
            confirmButton = {
                TextButton(onClick = { showStorageDialog = false }) {
                    Text("确认")
                }
            }
        )
    }
}


@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    MyAndriodInfoTheme {
        MainView("Android")
    }
}
