package com.cr.common

import android.annotation.TargetApi
import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore

/**
 * 操作系统：MAC系统
 * 创建者：王成
 * 创建日期：2023/6/16 10:32
 * 描述： 图片管理
 */
class CrPictureManager {
    companion object{
        /**
         * android4.4之前可直接获取图片真实uri
         * @param context Context 上下文
         * @param data Intent 数据
         * @return String
         */
        fun handleImageBeforeKitKat(context: Context,data: Intent):String {
            val uri = data.data
            return getImagePath(context!!,uri!!, null, null)!!
        }

        /**
         * android4.4之后，需要解析获取图片真实路径
         * @param context Context 上下文
         * @param data Intent 数据
         */
        @TargetApi(Build.VERSION_CODES.KITKAT)
        fun handleImageAfterKitKat(context: Context,data: Intent): String? {
            val uri = data.data
            // todo: 2023/6/16 document类型的Uri
            when {
                DocumentsContract.isDocumentUri(context, uri) -> {
                    // todo: 2023/6/16 通过documentId处理
                    val docId = DocumentsContract.getDocumentId(uri)
                    when (uri?.authority) {
                        "com.android.externalstorage.documents" -> {
                            val type = docId.split(":")[0]
                            if ("primary".equals(type, ignoreCase = true)) {
                                return Environment.getExternalStorageDirectory().toString() + "/" + docId.split(":")[1]
                            }
                        }
                        // todo: 2023/6/16 media类型解析
                        "com.android.providers.media.documents" -> {
                            val id = docId.split(":")[1]
                            val type = docId.split(":")[0]
                            val contentUri: Uri? = when (type) {
                                "image" -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                                "video" -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI
                                "audio" -> MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                                else -> null
                            }
                            val selection = "_id=?"
                            val selectionArgs: Array<String> = arrayOf(id)
                            return getImagePath(context!!,contentUri!!, selection, selectionArgs)
                        }
                        // todo: 2023/6/16 downloads文件解析
                        "com.android.providers.downloads.documents" -> {
                            ContentUris.withAppendedId(
                                Uri.parse("content://downloads/public_downloads"), docId.toLong()
                            ).apply {
                                return getImagePath(context!!,this, null, null)!!
                            }
                        }
                        else -> {
                        }
                    }
                }
                "content".equals(uri?.scheme, ignoreCase = true) ->
                    //content类型数据不需要解析，直接传入生成即可
                    return getImagePath(context!!,uri!!, null, null)
                "file".equals(uri?.scheme, ignoreCase = true) ->
                    //file类型的uri直接获取图片路径即可
                    return uri!!.path!!
            }
            return null
        }

        /**
         * 获取图片路径
         * @param context Context 上下文
         * @param uri Uri uri地址
         * @param selection String? 选择地址
         * @param selectionArgs Array<String>? 选择地址集
         * @return String?
         */
        private fun getImagePath(context: Context, uri: Uri, selection: String?, selectionArgs: Array<String>?): String? {
            var cursor: Cursor? = null
            try {
                cursor = context!!.contentResolver.query(uri, null, selection, selectionArgs, null)
                if (cursor?.moveToFirst()!!) {
                    return cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))
                }
            } finally {
                cursor?.close()
            }
            return null
        }
    }
}