package com.zxhy.hfilemanagermaster.knife

import android.content.ContentResolver
import android.content.ContentUris
import android.content.Context
import android.database.Cursor
import android.provider.MediaStore
import com.zxhy.hfilemanagermaster.data.MediaDataC
import java.io.File

fun Context.dupImage(): ArrayList<MediaDataC> {
    val list = arrayListOf<MediaDataC>()
    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)
    try {
        // 执行查询
        val contentResolver: ContentResolver = contentResolver
        cursor = contentResolver.query(uri, projection, null, null, null)

        // 遍历结果
        if (cursor != null && cursor.moveToFirst()) {
            do {
                // 获取照片的ID和名称
                val id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID))
                val name =
                    cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME))

                // 根据ID构建照片的Uri
                val photoUri = ContentUris.withAppendedId(uri, id)
                val filePath = getFilePathByUri(this, photoUri) ?: ""
                val md5 = File(filePath).digestMd5().byteArrayToHexString()
//            println(photoUri)
                list.add(MediaDataC(uri = photoUri, path = filePath, md5 = md5))
                // 在此处进行照片的操作，例如显示、复制、删除等
                // ...
//                if (list.size == 10) {
//                    break
//                }
            } while (cursor.moveToNext())
        } else {
            println("无数据")
        }
    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        cursor?.close()
    }
    return list
}