package com.iscs.bozzys.ui.pages.compose

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Paint
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.max

/**
 * 在部分老设备上没有效果
 */
@Composable
fun CardBox(
    modifier: Modifier = Modifier,
    topRadius: Dp = 12.dp,
    bottomRadius: Dp = 12.dp,
    shadowColor: Color = Color.Black.copy(alpha = 0.15f),
    shadowBlur: Dp = 10.dp,
    backgroundColor: Color = Color.White,
    content: @Composable BoxScope.() -> Unit
) {
    val density = LocalDensity.current

    Box(
        modifier = modifier
            // 强制软件渲染
            .graphicsLayer {
                this.renderEffect = null
                this.shadowElevation = 0f
            }
            .drawBehind {
                val radius = with(density) { max(topRadius, bottomRadius).toPx() }
                val blur = with(density) { shadowBlur.toPx() }

                drawIntoCanvas { canvas ->
                    val paint = Paint().asFrameworkPaint().apply {
                        isAntiAlias = true
                        color = backgroundColor.toArgb()
                        setShadowLayer(blur, 0f, 0f, shadowColor.toArgb())
                    }
                    canvas.nativeCanvas.drawRoundRect(0f, 0f, size.width, size.height, radius, radius, paint)
                }
            }
            .clip(RoundedCornerShape(topStart = topRadius, topEnd = topRadius, bottomStart = bottomRadius, bottomEnd = bottomRadius))
            // 内容背景
            .background(
                backgroundColor,
                RoundedCornerShape(topStart = topRadius, topEnd = topRadius, bottomStart = bottomRadius, bottomEnd = bottomRadius)
            )
    ) {
        content()
    }
}

