package com.base.easyfilemanager.utils

import android.annotation.SuppressLint
import android.content.ContentUris
import android.content.Context
import android.database.Cursor
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import com.base.easyfilemanager.bean.FileBean

object MediaStoreEx {
    fun recentImage(context: Context): ArrayList<Uri> {
        val list = arrayListOf<Uri>()
        var cursor: Cursor? = null
        // 查询照片的Uri和字段
        val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        val projection = arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME)
        //DESC 降列
        //ASC 升序
        val sortOrder = MediaStore.Images.ImageColumns._ID + " DESC"
        try {
            // 执行查询
            cursor = context.contentResolver.query(uri, projection, null, null, sortOrder)

            // 遍历结果
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    val id =
                        cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID))
                    list.add(ContentUris.withAppendedId(uri, id))
                    if (list.size == 10) {
                        break
                    }
                } while (cursor.moveToNext())
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            cursor?.close()
        }
        return list
    }

    fun recentVideo(context: Context): ArrayList<Uri> {
        val list = arrayListOf<Uri>()
        var cursor: Cursor? = null
        // 查询照片的Uri和字段
        val uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
        val projection = arrayOf(MediaStore.Video.Media._ID, MediaStore.Video.Media.DISPLAY_NAME)
        //DESC 降列
        //ASC 升序
        val sortOrder = MediaStore.Video.VideoColumns._ID + " DESC"
        try {
            // 执行查询
            cursor = context.contentResolver.query(uri, projection, null, null, sortOrder)

            // 遍历结果
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    val id =
                        cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID))
                    list.add(ContentUris.withAppendedId(uri, id))
                    if (list.size == 10) {
                        break
                    }
                } while (cursor.moveToNext())
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            cursor?.close()
        }
        return list
    }


    @SuppressLint("Range")
    fun Context.getAudioMedia(list: ArrayList<FileBean>): ArrayList<FileBean> {

        val projection = arrayOf(
            MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.ALBUM,
            MediaStore.Audio.Media.DATA,
            MediaStore.Audio.Media.DURATION,
            MediaStore.Audio.Media.SIZE
        )
        var cursor: Cursor? = null
        try {
            cursor = this.contentResolver.query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                projection,
                null,  // 选择条件，null表示查询所有
                null,  // 选择参数，配合选择条件使用
                MediaStore.Audio.Media.DEFAULT_SORT_ORDER // 排序顺序
            )

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    // 获取音乐文件的属性
                    val title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE))
                    val artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST))
                    val album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM))
                    val path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA))
                    val size = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE)).toLong()
                    // 其他属性...
                    list.add(FileBean(name = title, path = path, size))
                }
            }
        } catch (e: Exception) {

        } finally {
            cursor?.close()
        }
        return list
    }

    @SuppressLint("Range")
    fun Context.getImageMedia(list: ArrayList<FileBean>): ArrayList<FileBean> {
        val projection = arrayOf(
            MediaStore.Images.Media._ID,
            MediaStore.Images.Media.DATA,
            MediaStore.Images.Media.TITLE,
            MediaStore.Images.Media.MIME_TYPE,
            MediaStore.Images.Media.SIZE,
            MediaStore.Images.Media.DATE_TAKEN
        )
        var cursor: Cursor? = null
        try {
            cursor = contentResolver.query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection,
                null,  // 选择条件，null表示查询所有
                null,  // 选择参数，配合选择条件使用
                MediaStore.Images.Media.DATE_TAKEN + " DESC" // 按日期降序排序
            )

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    // 获取图片文件的属性
                    val title = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.TITLE))
                    val path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))
                    val size = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.SIZE)).toLong()
                    // 其他属性...
                    list.add(FileBean(title, path, size))
                }
                cursor.close()
            }
        } catch (e: Exception) {

        } finally {
            cursor?.close()
        }

        return list
    }

    @SuppressLint("Range")
    fun Context.getVideoMedia(list: ArrayList<FileBean>): ArrayList<FileBean> {
        val projection = arrayOf(
            MediaStore.Video.Media._ID,
            MediaStore.Video.Media.DATA,
            MediaStore.Video.Media.TITLE,
            MediaStore.Video.Media.MIME_TYPE,
            MediaStore.Video.Media.DURATION,
            MediaStore.Video.Media.DATE_TAKEN,
            MediaStore.Video.Media.SIZE,
        )

        var cursor: Cursor? = null
        try {
            cursor = contentResolver.query(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                projection,
                null,  // 选择条件，null表示查询所有
                null,  // 选择参数，配合选择条件使用
                MediaStore.Video.Media.DATE_TAKEN + " DESC" // 按日期降序排序
            )

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    // 获取视频文件的属性
                    val path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA))
                    val title = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.TITLE))
                    val size = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.SIZE)).toLong()
                    // 其他属性...
                    list.add(FileBean(title, path, size))
                }

            }
        } catch (e: Exception) {

        } finally {
            cursor?.close()
        }
        return list
    }

    @SuppressLint("Range")
    fun Context.geFileMedia(list: ArrayList<FileBean>, selectionArgs: Array<String>): ArrayList<FileBean> {
        val projection = arrayOf(
            MediaStore.Files.FileColumns._ID,
            MediaStore.Files.FileColumns.DATA,
            MediaStore.Files.FileColumns.MIME_TYPE,
            MediaStore.Files.FileColumns.TITLE,
            MediaStore.Files.FileColumns.SIZE,
        )

        // 选择条件，筛选出MIME类型为application/zip的文件
        val selection = MediaStore.Files.FileColumns.MIME_TYPE + "=?"
//        val selectionArgs = arrayOf("application/zip")

        var cursor: Cursor? = null
        try {
            cursor = contentResolver.query(
                MediaStore.Files.getContentUri("external"),  // 你也可以使用INTERNAL_CONTENT_URI来查询内部存储
                projection,
                selection,
                selectionArgs,
                null // 无排序
            )

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    val tittle = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.TITLE))
                    val path = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA))
                    val size = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.SIZE)).toLong()
                    // 其他属性...
                    list.add(FileBean(tittle, path, size))
                }
                cursor.close()
            }
        } catch (e: Exception) {

        } finally {
            cursor?.close()
        }

        return list
    }


    val commonMediaDir = arrayOf(
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).absolutePath,
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath,
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).absolutePath,
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).absolutePath,
    )

    fun Context.updateMediaStore(
        filePath: Array<String> = commonMediaDir
    ) {
        MediaScannerConnection.scanFile(
            this, filePath, null
        ) { path: String?, uri: Uri? -> }
    }

}

