package com.audio.record.screen.test.tool

import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.PixelFormat
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.media.Image
import android.media.ImageReader
import android.media.projection.MediaProjection
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import android.view.Gravity
import android.view.LayoutInflater
import android.view.WindowManager
import android.view.animation.DecelerateInterpolator
import android.widget.ImageView
import com.audio.record.screen.test.R
import com.audio.record.screen.test.service.ScreenshotAnimExecutor
import java.io.File
import java.io.FileOutputStream

/**
 * 截屏
 */
object ScreenCaptureHelper {

    private var virtualDisplay:VirtualDisplay? = null

    fun startScreenCapture(
        context: Context,
        mediaProjection: MediaProjection,
        folderName: String = Common.imagesFolderDir,
        isOK:(bitmap:Bitmap)->Unit
    ) {
        val metrics = Resources.getSystem().displayMetrics
        val full = Common.getFullScreenSize(context)
        val width = full.first
        val height = full.second
        val density = metrics.densityDpi

//        Common.showLog("startScreenCapture width=${width}, height=${height}  density=${density}  Thread=${Thread.currentThread().name}")
        val imageReader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 2)
        mediaProjection.registerCallback(object : MediaProjection.Callback() {
            override fun onStop() {
//                Common.showLog("startScreenCapture  MediaProjection 被系统或用户停止")
                // 这里应该释放 MediaRecorder 和 VirtualDisplay 等
                virtualDisplay?.release()
                mediaProjection.stop()

            }
        }, Handler(Looper.getMainLooper()))
        virtualDisplay = mediaProjection.createVirtualDisplay(
            "ScreenCapture",
            width, height, density,
            DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
            imageReader.surface, null, null
        )

        Handler(Looper.getMainLooper()).postDelayed({
            val image = imageReader.acquireLatestImage()
            if (image != null) {
                val bitmap = imageToBitmap(image)
                isOK.invoke(bitmap)
                saveBitmap(context, bitmap, folderName)

                image.close()
            }
            imageReader.close()
            virtualDisplay?.release()
            mediaProjection.stop()
        }, 100)
    }
    private fun imageToBitmap(image: Image): Bitmap {
        val width = image.width
        val height = image.height
        val plane = image.planes[0]
        val buffer = plane.buffer
        val pixelStride = plane.pixelStride
        val rowStride = plane.rowStride
        val rowPadding = rowStride - pixelStride * width

        val bitmap = Bitmap.createBitmap(
            width + rowPadding / pixelStride,
            height,
            Bitmap.Config.ARGB_8888
        )
        bitmap.copyPixelsFromBuffer(buffer)
        return Bitmap.createBitmap(bitmap, 0, 0, width, height)
    }
    private fun saveBitmap(context: Context, bitmap: Bitmap, folderName: String) {
        val fileName = "screenshot_${System.currentTimeMillis()}.png"

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10+
            val contentValues = ContentValues().apply {
                put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
                put(MediaStore.Images.Media.MIME_TYPE, "image/png")
                put(
                    MediaStore.Images.Media.RELATIVE_PATH,
                    folderName
                )
                put(MediaStore.Images.Media.IS_PENDING, 1)
            }

            val contentResolver = context.contentResolver
            val uri = contentResolver.insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                contentValues
            )

            uri?.let {
                contentResolver.openOutputStream(it)?.use { stream ->
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
                }
                contentValues.clear()
                contentValues.put(MediaStore.Images.Media.IS_PENDING, 0)
                contentResolver.update(uri, contentValues, null, null)
            }
        } else {
            // Android 7-9
            val picturesDir =
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
            val folder = File(folderName)
            if (!folder.exists()) folder.mkdirs()

            val file = File(folder, fileName)
            FileOutputStream(file).use { fos ->
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
            }

            // 通知媒体库刷新
            context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)))
        }
    }


    /**
     * 截屏的动画效果
     */
    fun showScreenshotPreviewAnimation(context: Context, screenshotBitmap: Bitmap,screenWidth:Int,screenHeight:Int) {
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager

        val inflate = LayoutInflater.from(context).inflate(R.layout.floating_screenshot_anim, null)
        val imageView = inflate.findViewById<ImageView>(R.id.image)
        imageView.setImageBitmap(screenshotBitmap)

        val layoutParams = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            else
                WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
                    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
            PixelFormat.TRANSLUCENT
        ).apply {
            gravity = Gravity.TOP or Gravity.START
        }
        windowManager.addView(inflate, layoutParams)
        val scale = 0.3f
        val targetWidth = (screenWidth * scale).toInt()
        val targetHeight = (screenHeight * scale).toInt()

        val targetX = screenWidth - targetWidth - 20
        val navigationBarHeight = Common.getNavigationBarHeight(context)
        val statusBarHeight = Common.getStatusBarHeight(context)
//        Common.showLog("navigationBarHeight=${navigationBarHeight}, statusBarHeight=${statusBarHeight} ")

        val targetY = screenHeight - targetHeight - navigationBarHeight - statusBarHeight - 20


//        Common.showLog("宽高 targetWidth=${targetWidth}, targetHeight=${targetHeight}  targetX = ${targetX} targetY = ${targetY}")


        val scaleX = ObjectAnimator.ofFloat(inflate, "scaleX", 1f, scale)
        val scaleY = ObjectAnimator.ofFloat(inflate, "scaleY", 1f, scale)
        val animatorSet = AnimatorSet()
        animatorSet.playTogether(scaleX, scaleY)
        animatorSet.duration = 50
        animatorSet.interpolator = DecelerateInterpolator()
        animatorSet.addListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {
                Common.showLog("-----动画开始")
            }

            override fun onAnimationEnd(animation: Animator) {
                // 更新 layoutParams 和结束逻辑...
                Common.showLog("-----动画结束")
                // 清除动画偏移
                inflate.scaleX = 1f
                inflate.scaleY = 1f
                inflate.translationX = 0f
                inflate.translationY = 0f

                // 更新 layoutParams 为最终目标位置与尺寸
                layoutParams.width = targetWidth
                layoutParams.height = targetHeight
                layoutParams.x = targetX
                layoutParams.y = targetY
                Common.showLog("动画结束 targetWidth=${targetWidth}, targetHeight=${targetHeight}  targetX = ${targetX} targetY = ${targetY}")
                windowManager.updateViewLayout(inflate, layoutParams)


                // 5秒后自动移除
                inflate.postDelayed({
                    try {
                        windowManager.removeView(inflate)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }, 3000)
            }

            override fun onAnimationCancel(animation: Animator) {}
            override fun onAnimationRepeat(animation: Animator) {}
        })
        animatorSet.start()
        inflate.setOnClickListener {
            Common.showLog("-----点击小截图")
        }

    }



    fun showScreenshotPreviewAnimationNew(context: Context, screenshotBitmap: Bitmap, screenWidth: Int, screenHeight: Int) {
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val inflate = LayoutInflater.from(context).inflate(R.layout.floating_screenshot_anim, null)
        val imageView = inflate.findViewById<ImageView>(R.id.image)
        imageView.setImageBitmap(screenshotBitmap)

        // 初始全屏展示
        val layoutParams = WindowManager.LayoutParams(
            screenWidth,
            screenHeight,
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            else
                WindowManager.LayoutParams.TYPE_PHONE,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                    WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
                    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
            PixelFormat.TRANSLUCENT
        ).apply {
            gravity = Gravity.TOP or Gravity.START
            x = 0
            y = 0
        }

        windowManager.addView(inflate, layoutParams)

        // 动画目标位置与缩放比例
        val scale = 0.25f
        val targetWidth = (screenWidth * scale).toInt()
        val targetHeight = (screenHeight * scale).toInt()
        val targetX = screenWidth - targetWidth - 32  // 留点边距
        val targetY = screenHeight - targetHeight - Common.getNavigationBarHeight(context) - 32

        // 设置原始位置（居中）
        inflate.pivotX = 0f
        inflate.pivotY = 0f
        inflate.translationX = 0f
        inflate.translationY = 0f
        inflate.scaleX = 1f
        inflate.scaleY = 1f

        // 执行缩放+位移动画
        inflate.animate()
            .scaleX(scale)
            .scaleY(scale)
            .translationX(targetX.toFloat())
            .translationY(targetY.toFloat())
            .setDuration(500)
            .setInterpolator(DecelerateInterpolator())
            .withStartAction {
                Common.showLog("📸 截图动画开始")
            }
            .withEndAction {
                Common.showLog("✅ 截图动画结束：变成小图")
                // 动画后清除 scale/translation 状态并更新窗口布局为小图位置
                inflate.scaleX = 1f
                inflate.scaleY = 1f
                inflate.translationX = 0f
                inflate.translationY = 0f

                layoutParams.width = targetWidth
                layoutParams.height = targetHeight
                layoutParams.x = targetX
                layoutParams.y = targetY
                windowManager.updateViewLayout(inflate, layoutParams)

                // 延时关闭
                inflate.postDelayed({
                    try {
                        windowManager.removeView(inflate)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }, 3000)
            }
            .start()

        inflate.setOnClickListener {
            Common.showLog("🖼️ 点击了截图缩略图")
        }
    }

}
