package com.example.base.extensions

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.ImageFormat
import android.graphics.Matrix
import android.graphics.Rect
import android.graphics.YuvImage
import android.media.Image
import android.view.View
import android.widget.LinearLayout
import java.io.ByteArrayOutputStream

fun View.toBitmap(): Bitmap? {
    // 获取布局的宽和高
    val width = measuredWidth
    val height = measuredHeight

    // 创建一个与FrameLayout大小相同的空Bitmap
    if (width <= 0 || height <= 0) return null // 防止宽度或高度为0时发生错误
    val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)

    // 创建一个新的Canvas用于将布局内容绘制到Bitmap上
    val canvas = Canvas(bitmap)

    // 将当前View绘制到Canvas上，从而将其内容渲染到Bitmap中
    draw(canvas)

    // 返回包含布局内容的Bitmap
    return bitmap
}

fun Image.toBitmaps(): Bitmap {
    val yBuffer = planes[0].buffer // Y
    val vuBuffer = planes[2].buffer // VU

    val ySize = yBuffer.remaining()
    val vuSize = vuBuffer.remaining()

    val nv21 = ByteArray(ySize + vuSize)

    yBuffer.get(nv21, 0, ySize)
    vuBuffer.get(nv21, ySize, vuSize)

    val yuvImage = YuvImage(nv21, ImageFormat.NV21, this.width, this.height, null)
    val out = ByteArrayOutputStream()
    yuvImage.compressToJpeg(Rect(0, 0, yuvImage.width, yuvImage.height), 50, out)
    val imageBytes = out.toByteArray()
    return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
}

fun rotateBitmap(bitmap: Bitmap, rotationDegrees: Int): Bitmap {
    val matrix = Matrix().apply {
        postRotate(rotationDegrees.toFloat())
    }
    return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
}

/**
 * 水印转bitmap
 */
fun renderWatermarkViewToBitmap(watermarkView: LinearLayout, width: Int, height: Int): Bitmap {
    watermarkView.measure(
        View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
        View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)
    )
    watermarkView.layout(0, 0, watermarkView.measuredWidth, watermarkView.measuredHeight)
    val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)
    watermarkView.draw(canvas)
    return bitmap
}

/**
 * 添加水印
 */
fun addWatermarkToImage(originalImage: Bitmap, watermarkBitmap: Bitmap, markX: Float, markY: Float): Bitmap {
    // 创建一个新的Bitmap，大小和原始图片一样
    val result = Bitmap.createBitmap(originalImage.width, originalImage.height, originalImage.config)
    val canvas = Canvas(result)
    // 绘制原始图片
    canvas.drawBitmap(originalImage, 0f, 0f, null)
    // 绘制水印
    canvas.drawBitmap(watermarkBitmap, markX, markY, null)
    return result
}
