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

import android.content.ContentUris
import android.content.ContentValues
import android.content.Context
import android.graphics.BitmapFactory
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.ParcelFileDescriptor
import android.provider.MediaStore
import android.util.DisplayMetrics
import android.util.Size
import android.view.WindowManager
import androidx.core.content.FileProvider
import com.audio.record.screen.test.data.ImageGroup
import com.audio.record.screen.test.data.ImageInfo
import com.audio.record.screen.test.data.VideoInfo
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

object VideoFileHelper {

    data class ScreenInfo(val width: Int, val height: Int, val dpi: Int)

    fun getScreenInfo(context: Context): ScreenInfo {
        val metrics = DisplayMetrics()
        val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            context.display?.getRealMetrics(metrics)
        } else {
            @Suppress("DEPRECATION")
            windowManager.defaultDisplay.getRealMetrics(metrics)
        }
        return ScreenInfo(metrics.widthPixels, metrics.heightPixels, metrics.densityDpi)
    }

    fun alignTo16(value: Int): Int = (value + 15) / 16 * 16


    /**
     * 创建一个用于 MediaRecorder 或其他输出的视频文件路径
     * @param context 上下文
     * @param folderName 你想要创建的文件夹名称（位于 Movies/ 下）
     * @param displayName 文件名（不含扩展名）
     * @return 文件的 Uri 和 FileDescriptor（可选）
     */
    fun createVideoFile(
        context: Context,
        folderName: String,
        displayName: String = "${System.currentTimeMillis()}"
    ): Pair<Uri, ParcelFileDescriptor?> {
        val resolver = context.contentResolver
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val contentValues = ContentValues().apply {
                put(MediaStore.Video.Media.DISPLAY_NAME, "$displayName.mp4")
                put(MediaStore.Video.Media.MIME_TYPE, "video/mp4")
                put(
                    MediaStore.Video.Media.RELATIVE_PATH,
                    Environment.DIRECTORY_MOVIES + "/$folderName"
                )
                put(MediaStore.Video.Media.IS_PENDING, 1)
            }

            val videoUri = resolver.insert(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                contentValues
            ) ?: throw IOException("无法创建视频文件 Uri")

            val pfd = try {
                resolver.openFileDescriptor(videoUri, "w")
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }

            return Pair(videoUri, pfd)
        } else {
            // Android 9及以下，使用旧方式（注意申请权限）
            val moviesDir =
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)
            val folder = File(moviesDir, folderName).apply { if (!exists()) mkdirs() }
            val file = File(folder, "$displayName.mp4").apply { if (!exists()) createNewFile() }

            val uri = FileProvider.getUriForFile(
                context,
                "${context.packageName}.fileprovider", // 记得配置 provider
                file
            )

            val pfd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_WRITE_ONLY)
            return Pair(uri, pfd)
        }

    }



    fun markVideoFileCompleted(context: Context, videoUri: Uri) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val resolver = context.contentResolver
            val contentValues = ContentValues().apply {
                put(MediaStore.Video.Media.IS_PENDING, 0)
            }
            resolver.update(videoUri, contentValues, null, null)
        }
    }


    /**
     * 遍历指定目录folderName下的所有视频
     */

    fun queryVideoInfoListInFolder(context: Context, folderName: String): List<VideoInfo> {
        val videoInfoList = mutableListOf<VideoInfo>()
        val resolver = context.contentResolver

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10+ 用 MediaStore 查询
            val projection = arrayOf(
                MediaStore.Video.Media._ID,
                MediaStore.Video.Media.DISPLAY_NAME,
                MediaStore.Video.Media.SIZE,
                MediaStore.Video.Media.DURATION,
                MediaStore.Video.Media.DATE_ADDED,
                MediaStore.Video.Media.DATE_MODIFIED
            )

            val selection = "${MediaStore.Video.Media.RELATIVE_PATH} = ?"
            val selectionArgs = arrayOf("$folderName/")

            val sortOrder = "${MediaStore.Video.Media.DATE_ADDED} DESC"

            resolver.query(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                projection,
                selection,
                selectionArgs,
                sortOrder
            )?.use { cursor ->
                val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID)
                val nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME)
                val sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE)
                val durationColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION)
                val dateAddedColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_ADDED)
                val dateModifiedColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATE_MODIFIED)

                while (cursor.moveToNext()) {
                    val id = cursor.getLong(idColumn)
                    val uri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id)
                    val displayName = cursor.getString(nameColumn)
                    val size = cursor.getLong(sizeColumn)
                    val duration = cursor.getLong(durationColumn)
                    val dateAdded = cursor.getLong(dateAddedColumn)
                    val dateModified = cursor.getLong(dateModifiedColumn)

                    // 获取封面图 (Android Q+ 推荐用 loadThumbnail)
                    val thumbnail = try {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                            resolver.loadThumbnail(uri, Size(1280,720), null)
                        } else {
                            null
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                        null
                    }

                    val videoInfo = VideoInfo(
                        uri = uri,
                        displayName = displayName,
                        size = size,
                        duration = duration,
                        dateAdded = dateAdded,
                        dateModified = dateModified,
                        thumbnail = thumbnail
                    )

                    videoInfoList.add(videoInfo)
                }
            }
        } else {
            // Android 9 及以下，File API 查询
            val folderPath = Environment.getExternalStoragePublicDirectory(
                folderName
            ).absolutePath

            val folder = File(folderPath)
            if (folder.exists() && folder.isDirectory) {
                val videoFiles = folder.listFiles { file ->
                    file.isFile && file.extension.equals("mp4", ignoreCase = true)
                }?.toList() ?: emptyList()

                videoFiles.forEach { file ->
                    val uri = FileProvider.getUriForFile(
                        context,
                        "${context.packageName}.fileprovider",
                        file
                    )

                    // 获取视频基本信息（只能通过 MediaMetadataRetriever 获取部分信息）
                    val retriever = MediaMetadataRetriever()
                    retriever.setDataSource(context, uri)

                    val duration = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: 0L
                    val thumbnail = try {
                        retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC)
                    } catch (e: Exception) {
                        e.printStackTrace()
                        null
                    }

                    retriever.release()

                    val videoInfo = VideoInfo(
                        uri = uri,
                        displayName = file.name,
                        size = file.length(),
                        duration = duration,
                        dateAdded = file.lastModified() / 1000,
                        dateModified = file.lastModified() / 1000,
                        thumbnail = thumbnail
                    )

                    videoInfoList.add(videoInfo)
                }
            }
        }

        return videoInfoList
    }




    /**
     * 遍历指定目录folderName下的所有图片
     */
   private fun queryImagesInFolder(context: Context, folderName: String): List<ImageInfo> {
        Common.showLog("-----图片-folderName=${folderName}")
        val imageInfoList = mutableListOf<ImageInfo>()
        val resolver = context.contentResolver

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val projection = arrayOf(
                MediaStore.Images.Media._ID,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.SIZE,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Media.DATE_MODIFIED
            )

            val selection = "${MediaStore.Images.Media.RELATIVE_PATH} = ?"
            val selectionArgs = arrayOf("$folderName/")

            val sortOrder = "${MediaStore.Images.Media.DATE_ADDED} DESC"

            resolver.query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection,
                selection,
                selectionArgs,
                sortOrder
            )?.use { cursor ->
                val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
                val nameColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)
                val sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE)
                val dateAddedColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_ADDED)
                val dateModifiedColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_MODIFIED)

                while (cursor.moveToNext()) {
                    val id = cursor.getLong(idColumn)
                    val uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)
                    val displayName = cursor.getString(nameColumn)
                    val size = cursor.getLong(sizeColumn)
                    val dateAdded = cursor.getLong(dateAddedColumn)
                    val dateModified = cursor.getLong(dateModifiedColumn)

                    val thumbnail = try {
                        resolver.loadThumbnail(uri, Size(320, 320), null)
                    } catch (e: Exception) {
                        null
                    }
                    Common.showLog("-----图片-displayName=${displayName}")
                    val info = ImageInfo(
                        uri = uri,
                        displayName = displayName,
                        size = size,
                        dateAdded = dateAdded,
                        dateModified = dateModified,
                        thumbnail = thumbnail
                    )
                    imageInfoList.add(info)
                }
            }
        } else {
            // Android 7-9 (API 24~28)，用 File API
            val folder = File(folderName)

            if (folder.exists() && folder.isDirectory) {
                val files = folder.listFiles { file ->
                    file.isFile && (file.extension.equals("jpg", true)
                            || file.extension.equals("png", true)
                            || file.extension.equals("jpeg", true))
                }?.toList() ?: emptyList()

                files.forEach { file ->
                    val uri = FileProvider.getUriForFile(
                        context,
                        "${context.packageName}.fileprovider",
                        file
                    )

                    val bitmap = try {
                        BitmapFactory.decodeFile(file.absolutePath)
                    } catch (e: Exception) {
                        null
                    }

                    val info = ImageInfo(
                        uri = uri,
                        displayName = file.name,
                        size = file.length(),
                        dateAdded = file.lastModified() / 1000,
                        dateModified = file.lastModified() / 1000,
                        thumbnail = bitmap
                    )
                    imageInfoList.add(info)
                }
            }
        }

        return imageInfoList
    }


    fun queryGroupedImagesByDay(context: Context, folderName: String): List<ImageGroup> {
        val allImages = queryImagesInFolder(context, folderName)
        Common.showLog("-----图片-allImages=${allImages.size}")
        // 分组处理：按 dateAdded 转换为 yyyy-MM-dd
        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())

        return allImages
            .groupBy { image ->
                val date = Date(image.dateAdded * 1000) // 秒 → 毫秒
                dateFormat.format(date)
            }
            .map { (date, images) ->
                ImageGroup(date, images)
            }
            .sortedByDescending { it.date } // 按日期倒序排
    }

    fun groupVideosByDay(videoList: List<VideoInfo>): Map<String, List<VideoInfo>> {
        val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())

        return videoList.groupBy { video ->
            val timestampMillis = video.dateAdded * 1000 // 秒转毫秒
            sdf.format(Date(timestampMillis)) // 格式化成日期字符串
        }
    }

}
