package com.dong.demo013.Log

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import com.dong.demo013.pirntRandomHiLog
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlin.time.TimeSource

private const val TIMER_MAX_SECONDS = 20 * 60L // 20 分钟上限

@OptIn(ExperimentalLayoutApi::class)
@Composable
internal fun HighLogDemo() {
    // 日志参数状态
    var logSpeed by remember { mutableStateOf("1000") }
    var logCount by remember { mutableStateOf(0) }
    var isGenerating by remember { mutableStateOf(false) }
    
    // 计时器状态 - 使用纯 Compose 方式实现
    var displayTime by remember { mutableStateOf(0L) }
    var isTimerRunning by remember { mutableStateOf(false) }
    val timeSource = remember { TimeSource.Monotonic }
    var startTimeMark by remember { mutableStateOf(timeSource.markNow()) }
    
    // 使用 LaunchedEffect 实现计时器，达到 20 分钟自动停止
    LaunchedEffect(isTimerRunning) {
        if (isTimerRunning) {
            startTimeMark = timeSource.markNow()
            while (isActive && isTimerRunning) {
                delay(1000) // 每 1000ms 更新一次显示
                val elapsed = startTimeMark.elapsedNow().inWholeSeconds
                displayTime = elapsed
                if (elapsed >= TIMER_MAX_SECONDS) {
                    isTimerRunning = false
                    isGenerating = false
                    displayTime = TIMER_MAX_SECONDS
                    break
                }
            }
        } else {
            // 暂停时重置时间
            displayTime = 0
        }
    }
    
    // 日志生成协程
    LaunchedEffect(isGenerating, logSpeed) {
        if (isGenerating) {
            val speed = logSpeed.toIntOrNull() ?: 1000
            while (isActive && isGenerating) {
                delay(speed.toLong())
                logCount++
                pirntRandomHiLog()
            }
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.spacedBy(16.dp)
    ) {
        // 计时器显示区域
        Card(backgroundColor = MaterialTheme.colors.surface) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
            ) {
                Text(
                    "运行时间（上限 20 分钟）",
                    style = MaterialTheme.typography.h6,
                    modifier = Modifier.padding(bottom = 12.dp)
                )

                // 时间显示
                Card(
                    backgroundColor = MaterialTheme.colors.primary.copy(alpha = 0.1f),
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Text(
                            "${displayTime}秒",
                            style = MaterialTheme.typography.h4,
                            color = MaterialTheme.colors.primary
                        )
                        if (isGenerating) {
                            Text(
                                "日志生成中...",
                                style = MaterialTheme.typography.caption,
                                color = MaterialTheme.colors.secondary
                            )
                        }
                    }
                }
            }
        }

        // 日志生成功能区域
        Card(backgroundColor = MaterialTheme.colors.surface) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
            ) {
                Text(
                    "日志生成工具",
                    style = MaterialTheme.typography.h6,
                    modifier = Modifier.padding(bottom = 12.dp)
                )

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    OutlinedTextField(
                        value = logSpeed,
                        onValueChange = { newValue ->
                            // 只允许数字输入
                            if (newValue.all { it.isDigit() }) {
                                logSpeed = newValue
                            }
                        },
                        label = { Text("间隔(ms)") },
                        modifier = Modifier.weight(1f),
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                        singleLine = true
                    )
                }

                Spacer(Modifier.height(12.dp))

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Button(
                        onClick = {
                            // 启动日志生成和计时器
                            logCount = 0
                            isGenerating = true
                            isTimerRunning = true
                        },
                        modifier = Modifier.weight(1f),
                        enabled = logSpeed.isNotEmpty() && !isGenerating
                    ) {
                        Text("开始生成")
                    }
                    
                    Button(
                        onClick = {
                            // 停止日志生成和计时器
                            isGenerating = false
                            isTimerRunning = false
                        },
                        modifier = Modifier.weight(1f),
                        enabled = isGenerating
                    ) {
                        Text("停止生成")
                    }
                }

                // 显示日志生成状态
                if (isGenerating || logCount > 0) {
                    Spacer(Modifier.height(12.dp))
                    Card(
                        backgroundColor = MaterialTheme.colors.secondary.copy(alpha = 0.1f),
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        Column(
                            modifier = Modifier.padding(12.dp),
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Text(
                                "生成日志数量",
                                style = MaterialTheme.typography.subtitle1,
                                color = MaterialTheme.colors.secondary
                            )
                            Text(
                                "$logCount 条",
                                style = MaterialTheme.typography.h4,
                                color = MaterialTheme.colors.secondary,
                                modifier = Modifier.padding(top = 4.dp)
                            )
                        }
                    }
                }
            }
        }
    }
}