import android.content.Context
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import coil3.ImageLoader
import coil3.compose.rememberAsyncImagePainter
import coil3.disk.DiskCache
import coil3.memory.MemoryCache
import coil3.request.ImageRequest
import coil3.request.crossfade
import okio.Path.Companion.toPath

data class ImageItem(val url: String)

@Composable
fun ImageListScreen(context: Context, imageList: List<ImageItem>) {
    val imageLoader = getImageLoader(context)

    LazyColumn(
        modifier = Modifier.fillMaxSize(),
        contentPadding = PaddingValues(16.dp)
    ) {
        items(imageList) { item ->
            ImageItem(item, imageLoader, context) // 传递 context 参数
        }
    }
}

@Composable
fun ImageItem(item: ImageItem, imageLoader: ImageLoader, context: Context) { // 接收 context 参数
    val painter = rememberAsyncImagePainter(
        model = ImageRequest.Builder(context) // 使用 context 参数
            .data(item.url)
            .crossfade(true)
            .build(),
        imageLoader = imageLoader
    )

    Image(
        painter = painter,
        contentDescription = null,
        modifier = Modifier
            .fillMaxWidth()
            .height(200.dp),
        contentScale = ContentScale.Crop
    )
    Spacer(modifier = Modifier.height(16.dp))
}

fun getImageLoader(context: Context): ImageLoader {
    return ImageLoader.Builder(context)
        .memoryCache {
            MemoryCache.Builder()
                .maxSizePercent(context,0.25) // 设置内存缓存大小为可用内存的 25%
                .build()
        }
        .diskCache {
            val cacheDir = context.cacheDir.resolve("image_cache")
            DiskCache.Builder()
                .directory(cacheDir.absolutePath.toPath())
                .maxSizeBytes(250L * 1024 * 1024) // 250MB
                .build()
        }
        .build()
}