package com.zxhy.solarmasterace.quicktools

import android.content.ContentUris
import android.content.Context
import android.database.Cursor
import android.provider.MediaStore
import com.zxhy.solarmasterace.data.FileBean

fun recentImage(context: Context): ArrayList<FileBean> {
    val list = arrayListOf<FileBean>()
    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))
                val photoUri = ContentUris.withAppendedId(uri, id)
                list.add(FileBean(uri = photoUri))
                if (list.size == 10) {
                    break
                }
            } while (cursor.moveToNext())
        }
    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        cursor?.close()
    }
    return list
}